void operator() ( const MDagPath &dagPath, IECore::SceneInterface::NameList &attributes ) { MString p = dagPath.fullPathName(); IECorePython::ScopedGILLock gilLock; object o; try { o = m_names( p.asChar() ); } catch ( error_already_set ) { PyErr_Print(); throw IECore::Exception( std::string( "Python exception while evaluating attribute names for IECoreMaya::LiveScene." ) ); } extract<list> l( o ); if ( !l.check() ) { throw IECore::InvalidArgumentException( std::string( "Invalid value! Expecting a list of strings." ) ); } IECorePython::listToSceneInterfaceNameList( l(), attributes ); }
void Renderer::write( /*const*/ liqRibLocatorData* pData, const MString &fileName, const structJob ¤tJob, const bool bReference) { CM_TRACE_FUNC("Renderer::write("<<pData->getFullPathName().asChar()<<","<<fileName.asChar()<<","<<currentJob.name.asChar()<<",ref="<<bReference<<")"); if( !bReference ){//write data at first time assert(pData->getRibFileFullPath().length()==0); pData->setRibFileFullPath(fileName); // renderman::Helper o; // o.RiBeginRef(pData->getRibFileFullPath().asChar()); _write(pData, currentJob); // o.RiEndRef(); }else{ //write the reference assert(pData->getRibFileFullPath() == fileName); // RiReadArchive( const_cast< RtToken >( pData->getRibFileFullPath().asChar() ), NULL, RI_NULL ); } }
void decreaseFileRef(const MFileObject& file) { MString resolvedFullName = file.resolvedFullName(); std::string key = resolvedFullName.asChar(); tbb::unique_lock<tbb::mutex> lock(fMutex); // look up the file ref count FileRefCountIterator fileRefCountIter = fFileRefCount.find(key); if (fileRefCountIter != fFileRefCount.end()) { // decrease the file ref count if (--(*fileRefCountIter).second == 0) { // file ref count reaches 0 // purge this reader from cache since the reader won't // be referenced any more // the reader may already be closed because of the capacity fFileRefCount.erase(fileRefCountIter); LeftIterator iter = fData.left.find(key); if (iter != fData.left.end()) { fData.left.erase(iter); } } } }
void Renderer::write( /*const*/ liqRibMeshData* pData, const MString &ribFileName, const structJob ¤tJob, const bool bReference) { CM_TRACE_FUNC("Renderer::write("<<pData->getFullPathName().asChar()<<","<<ribFileName.asChar()<<","<<currentJob.name.asChar()<<",ref="<<bReference<<")"); assert(liqglo.m_ribFileOpen&&"rm_writeMeshData.cpp"); if(liqglo.m_writeDataIntoMainRibFile) { if( bReference ){ _write(pData, currentJob); }else{ //do nothing } }else{ if( !bReference ){//write data at first time if( currentJob.pass != rpShadowMap ){ assert(pData->getRibFileFullPath().length()==0&&"rm_writeMeshData.cpp"); } pData->setRibFileFullPath(ribFileName); renderman::Helper o; o.RiBeginRef(pData->getRibFileFullPath().asChar()); _write(pData, currentJob); o.RiEndRef(); }else{ //write the reference assert(pData->getRibFileFullPath() == ribFileName); RiReadArchive( const_cast< RtToken >( pData->getRibFileFullPath().asChar() ), NULL, RI_NULL ); } } }
static void _GatherPrefixedAttrs( const std::map<std::string, std::string>& attrPrefixes, const std::map<std::string, std::string>& primvarPrefixes, const MDagPath &dag, std::vector<_AttributeEntry>* attrs) { MStatus status; MFnDependencyNode depFn(dag.node()); unsigned int numAttrs = depFn.attributeCount(); for (unsigned int i=0; i < numAttrs; ++i) { MObject attrObj = depFn.attribute(i); MPlug plg = depFn.findPlug(attrObj, true); if (plg.isNull()) { continue; } // Skip if not dynamic attr (user attribute) if (!plg.isDynamic()) { continue; } MString mayaPlgName = plg.partialName(false, false, false, false, false, true, &status); std::string plgName(mayaPlgName.asChar()); // Skip if it's an AbcExport-suffixed hint attribute. if (_EndsWithAbcTag(plgName)) { continue; } // Add entries based on attribute prefix list and primvar prefix list. _AddAttributeNameEntry(plgName, attrPrefixes, false, attrs); _AddAttributeNameEntry(plgName, primvarPrefixes, true, attrs); } }
//----------------------------------------------------------------------------- // Exports a Maya file to a DMX file //----------------------------------------------------------------------------- bool CMayaDmeMakefileUtils::PerformCompilationStep( CDmeMayaMakefile *pMakeFile, CompilationStep_t step ) { if ( step != BEFORE_COMPILATION ) return BaseClass::PerformCompilationStep( pMakeFile, step ); MString currentFile = MFileIO::currentFile(); int nCount = pMakeFile->GetSourceCount(); for ( int i = 0; i < nCount; ++i ) { CDmeSourceMayaFile *pMayaSource = CastElement< CDmeSourceMayaFile >( pMakeFile->GetSource(i) ); if ( !pMayaSource ) continue; char pSourcePath[MAX_PATH]; pMakeFile->GetSourceFullPath( pMayaSource, pSourcePath, sizeof(pSourcePath) ); // Maya wants forward slashes Q_FixSlashes( pSourcePath, '/' ); if ( Q_stricmp( currentFile.asChar(), pSourcePath ) ) continue; // It's already open MString command = "saveChanges(\"\")"; g_pMayaVGui->SetModalMode( true ); int nResult; MStatus status = MGlobal::executeCommand( command, nResult ); g_pMayaVGui->SetModalMode( false ); if ( status != MStatus::kSuccess || ( nResult == 0 ) ) return false; break; } return BaseClass::PerformCompilationStep( pMakeFile, step ); }
MayaPointPrimitiveWriter::MayaPointPrimitiveWriter( double iFrame, MDagPath & iDag, Alembic::AbcGeom::OObject & iParent, Alembic::Util::uint32_t iTimeIndex, const JobArgs & iArgs) : mIsAnimated(false), mDagPath(iDag) { MFnParticleSystem particle(mDagPath); MString name = particle.name(); name = util::stripNamespaces(name, iArgs.stripNamespace); Alembic::AbcGeom::OPoints obj(iParent, name.asChar(), iTimeIndex); mSchema = obj.getSchema(); Alembic::Abc::OCompoundProperty cp; Alembic::Abc::OCompoundProperty up; if (AttributesWriter::hasAnyAttr(particle, iArgs)) { cp = mSchema.getArbGeomParams(); up = mSchema.getUserProperties(); } mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, particle, iTimeIndex, iArgs, true)); MObject object = iDag.node(); if (iTimeIndex != 0 && util::isAnimated(object)) { mIsAnimated = true; } if (!mIsAnimated || iArgs.setFirstAnimShape) { write(iFrame); } }
renderer::Assembly* createAssembly(const MayaObject* obj) { MayaObject* assemblyObject = getAssemblyMayaObject(obj); boost::shared_ptr<AppleseedRenderer> appleRenderer = boost::static_pointer_cast<AppleseedRenderer>(getWorldPtr()->mRenderer); renderer::Assembly* master = getMasterAssemblyFromProject(appleRenderer->getProjectPtr()); if (obj->mobject.hasFn(MFn::kLight) && !obj->mobject.hasFn(MFn::kAreaLight)) return master; if (assemblyObject == 0) return master; MString assemblyName = getAssemblyName(assemblyObject); if (assemblyName == "world") return master; foundation::auto_release_ptr<renderer::Assembly> assembly( renderer::AssemblyFactory().create(assemblyName.asChar(), renderer::ParamArray())); renderer::Assembly* ass = assembly.get(); master->assemblies().insert(assembly); return ass; }
MStatus OSGFileTranslator::writer( const MFileObject &file, const MString &optionsString, MPxFileTranslator::FileAccessMode mode ) { // Set Config ExportSelection Attribute if ( ( mode == MPxFileTranslator::kExportAccessMode ) || ( mode == MPxFileTranslator::kSaveAccessMode ) ) Config::instance()->setExportSelection( false ) ; else if( mode == MPxFileTranslator::kExportActiveAccessMode ) Config::instance()->setExportSelection( true ) ; // the first character in the optinsString is a ";", so get rid of it with substring MString options = optionsString.substring( 1 , optionsString.length() -1 ) ; MStringArray argStringArray ; std::cout << optionsString.asChar() ; // split the String with " " to get and option Array MStatus status = options.split( ' ' , argStringArray ) ; OSGWrite::parseArgs( argStringArray ) ; OSGWrite::exporta( file.expandedFullName() ) ; return MStatus::kSuccess; }
MStatus MayaRenderView::doIt( const MArgList& args) { MArgDatabase argData(syntax(), args); if(argData.isFlagSet( "-camera")) { MString camera; argData.getFlagArgument("-camera", 0, camera); _camera = std::string(camera.asChar()); } if(argData.isFlagSet( "-width")) { unsigned int width; argData.getFlagArgument("-width",0,width); _resolution.x() = width; } if(argData.isFlagSet( "-height")) { unsigned int height; argData.getFlagArgument("-height",0,height); _resolution.y() = height; } return redoIt(); }
MStatus octreeVizNode::compute( const MPlug& plug, MDataBlock& data ) { MStatus status; if(plug == aoutput) { double time = data.inputValue(acurrenttime).asTime().value(); int frame_lo = time + 0.005; if(frame_lo < 3) frame_lo = 3; if(frame_lo >60) frame_lo = 60; MString sname = data.inputValue(aHDRName).asString(); sname = "/Users/jianzhang/Documents/maya/projects/default/data/untitled"; char filename[512]; sprintf( filename, "%s.%d.pmap", sname.asChar(), frame_lo ); sname = filename; MGlobal::displayInfo(sname); if(sname != m_gridname) { m_gridname = sname; if(m_pTex) delete m_pTex; m_pTex = new Z3DTexture; if(m_pTex->load(m_gridname.asChar())) { zDisplayFloat(m_pTex->getNumGrid()); zDisplayFloat(m_pTex->getNumVoxel()); zDisplayFloat(m_pTex->getMaxLevel()); m_pTex->setDraw(); } } data.setClean(plug); } return MS::kUnknownParameter; }
MStatus liqIPRNodeMessage::doIt( const MArgList& args) // // Takes the nodes that are on the active selection list and adds an // attriubte changed callback to each one. // { MStatus stat; for( unsigned i( 0 ); i < args.length(); i++ ) { MString arg = args.asString( i, &stat ); IfMErrorWarn(stat); if( (arg == kRegisterFlag) || (arg == kRegisterFlagLong) ){ isRunningIPR = 1; liqRibTranslator::getInstancePtr()->IPRRenderBegin(); IfMErrorWarn(registerCallback()); //liqRibTranslator::getInstancePtr()->IPRDoIt(); } else if( (arg == kUnregisterFlag) || (arg == kUnregisterFlagLong) ){ IfMErrorWarn(unregisterCallback()); liqRibTranslator::getInstancePtr()->IPRRenderEnd(); isRunningIPR = 0; } else if( (arg == kIsRunningIPR) || (arg == kIsRunningIPRLong) ){ setResult(isRunningIPR); } else{ liquidMessage2(messageError,"Parameter [%s] is undefined in liqIPRNodeMessage.", arg.asChar()); return MS::kUnknownParameter; } } return MS::kSuccess; }
MStatus atomExport::writer( const MFileObject& file, const MString& options, FileAccessMode mode) { MStatus status = MS::kFailure; MString fileName = file.fullName(); #if defined (OSMac_) char fname[MAXPATHLEN]; strcpy (fname, fileName.asChar()); ofstream animFile(fname); #else ofstream animFile(fileName.asChar()); #endif // Defaults. // MString copyFlags("copyKey -cb api -fea 1 "); int precision = kDefaultPrecision; bool statics = false; bool includeChildren = false; std::set<std::string> attrStrings; // Parse the options. The options syntax is in the form of // "flag=val;flag1=val;flag2=val" // bool useSpecifiedRange = false; bool useTemplate = false; bool cached = false; bool constraint = false; bool sdk = false; bool animLayers = true; MString templateName; MString viewName; MTime startTime = MAnimControl::animationStartTime(); MTime endTime = MAnimControl::animationEndTime(); MString exportEditsFile; MString exportFlags; if (options.length() > 0) { const MString flagPrecision("precision"); const MString flagStatics("statics"); const MString flagConstraint("constraint"); const MString flagSDK("sdk"); const MString flagAnimLayers("animLayers"); const MString flagCopyKeyCmd("copyKeyCmd"); const MString flagSelected("selected"); const MString flagTemplate("template"); const MString flagView("view"); const MString optionChildrenToo("childrenToo"); const MString optionTemplate("template"); const MString flagAttr("at"); const MString flagWhichRange("whichRange"); const MString flagRange("range"); const MString flagExportEdits("exportEdits"); const MString flagCached("baked"); // Start parsing. // MStringArray optionList; MStringArray theOption; options.split(';', optionList); unsigned nOptions = optionList.length(); for (unsigned i = 0; i < nOptions; i++) { theOption.clear(); optionList[i].split('=', theOption); if (theOption.length() < 1) { continue; } if (theOption[0] == flagPrecision && theOption.length() > 1) { if (theOption[1].isInt()) { precision = theOption[1].asInt(); } } else if( theOption[0] == flagTemplate && theOption.length() > 1) { templateName = theOption[1]; } else if( theOption[0] == flagView && theOption.length() > 1) { viewName = theOption[1]; } else if ( theOption[0] == flagWhichRange && theOption.length() > 1) { if (theOption[1].isInt()) useSpecifiedRange = (theOption[1].asInt() ==1) ? false : true; } else if ( theOption[0] == flagRange && theOption.length() > 1) { MStringArray rangeArray; theOption[1].split(':',rangeArray); if(rangeArray.length()==2) { if(rangeArray[0].isDouble()) { double val = rangeArray[0].asDouble(); startTime = MTime(val,MTime::uiUnit()); } else if(rangeArray[0].isInt()) { double val = (double)rangeArray[0].asInt(); startTime = MTime(val,MTime::uiUnit()); } if(rangeArray[1].isDouble()) { double val = rangeArray[1].asDouble(); endTime = MTime(val,MTime::uiUnit()); } else if(rangeArray[1].isInt()) { double val = (double)rangeArray[1].asInt(); endTime = MTime(val,MTime::uiUnit()); } } } else if ( theOption[0] == flagStatics && theOption.length() > 1) { if (theOption[1].isInt()) { statics = (theOption[1].asInt()) ? true : false; } } else if ( theOption[0] == flagSDK && theOption.length() > 1) { if (theOption[1].isInt()) { sdk = (theOption[1].asInt()) ? true : false; } } else if ( theOption[0] == flagConstraint && theOption.length() > 1) { if (theOption[1].isInt()) { constraint = (theOption[1].asInt()) ? true : false; } } else if ( theOption[0] == flagAnimLayers && theOption.length() > 1) { if (theOption[1].isInt()) { animLayers = (theOption[1].asInt()) ? true : false; } } else if ( theOption[0] == flagCached && theOption.length() > 1) { if (theOption[1].isInt()) { cached = (theOption[1].asInt()) ? true : false; } } else if (theOption[0] == flagSelected && theOption.length() > 1) { includeChildren = (theOption[1] == optionChildrenToo) ? true : false; if(theOption[1] == optionTemplate) useTemplate = true; } else if (theOption[0] == flagAttr && theOption.length() > 1) { std::string str(theOption[1].asChar()); attrStrings.insert(str); } else if ( theOption[0] == flagCopyKeyCmd && theOption.length() > 1) { // Replace any '>' characters with '"'. This is needed // since the file translator option boxes do not handle // escaped quotation marks. // const char *optStr = theOption[1].asChar(); size_t nChars = strlen(optStr); char *copyStr = new char[nChars+1]; copyStr = strcpy(copyStr, optStr); for (size_t j = 0; j < nChars; j++) { if (copyStr[j] == '>') { copyStr[j] = '"'; } } copyFlags += copyStr; delete [] copyStr; } else if (theOption[0] == flagExportEdits && theOption.length() > 1) { exportEditsFile = theOption[1]; } } } // Set the precision of the ofstream. // animFile.precision(precision); atomTemplateReader templateReader; if(useTemplate == true) { includeChildren = false; templateReader.setTemplate(templateName,viewName); templateReader.selectNodes(); //make the template nodes be the selection } status = exportSelected(animFile, copyFlags, attrStrings, includeChildren, useSpecifiedRange, startTime, endTime, statics, cached,sdk,constraint, animLayers, exportEditsFile,templateReader); animFile.flush(); animFile.close(); return status; }
depthShaderOverride::depthShaderOverride(const MObject& obj) : MPxSurfaceShadingNodeOverride(obj) , fFragmentName("") { // Define fragments needed for VP2 version of shader, this could also be // defined in a separate XML file // // Define the input and output parameter names to match the input and // output attribute names so that the values are automatically populated // on the shader. // // Define a separate fragment for computing the camera space position so // that the operation can be done in the vertex shader rather than the // pixel shader. Then connect the two fragments together in a graph. static const MString sFragmentName("depthShaderPluginFragment"); static const char* sFragmentBody = "<fragment uiName=\"depthShaderPluginFragment\" name=\"depthShaderPluginFragment\" type=\"plumbing\" class=\"ShadeFragment\" version=\"1.0\">" " <description><![CDATA[Depth shader fragment]]></description>" " <properties>" " <float name=\"depthValue\" />" " <float3 name=\"color\" />" " <float3 name=\"colorFar\" />" " <float name=\"near\" />" " <float name=\"far\" />" " </properties>" " <values>" " <float name=\"depthValue\" value=\"0.0\" />" " <float3 name=\"color\" value=\"0.0,1.0,0.0\" />" " <float3 name=\"colorFar\" value=\"0.0,0.0,1.0\" />" " <float name=\"near\" value=\"0.0\" />" " <float name=\"far\" value=\"2.0\" />" " </values>" " <outputs>" " <float3 name=\"outColor\" />" " </outputs>" " <implementation>" " <implementation render=\"OGSRenderer\" language=\"Cg\" lang_version=\"2.1\">" " <function_name val=\"depthShaderPluginFragment\" />" " <source><![CDATA[" "float3 depthShaderPluginFragment(float depthValue, float3 cNear, float3 cFar, float nearClip, float farClip) \n" "{ \n" " float ratio = (farClip + depthValue)/(farClip - nearClip); \n" " return cNear*ratio + cFar*(1.0f - ratio); \n" "} \n]]>" " </source>" " </implementation>" " <implementation render=\"OGSRenderer\" language=\"HLSL\" lang_version=\"11.0\">" " <function_name val=\"depthShaderPluginFragment\" />" " <source><![CDATA[" "float3 depthShaderPluginFragment(float depthValue, float3 cNear, float3 cFar, float nearClip, float farClip) \n" "{ \n" " float ratio = (farClip + depthValue)/(farClip - nearClip); \n" " return cNear*ratio + cFar*(1.0f - ratio); \n" "} \n]]>" " </source>" " </implementation>" " <implementation render=\"OGSRenderer\" language=\"GLSL\" lang_version=\"3.0\">" " <function_name val=\"depthShaderPluginFragment\" />" " <source><![CDATA[" "vec3 depthShaderPluginFragment(float depthValue, vec3 cNear, vec3 cFar, float nearClip, float farClip) \n" "{ \n" " float ratio = (farClip + depthValue)/(farClip - nearClip); \n" " return cNear*ratio + cFar*(1.0f - ratio); \n" "} \n]]>" " </source>" " </implementation>" " </implementation>" "</fragment>"; static const MString sVertexFragmentName("depthShaderPluginInterpolantFragment"); static const char* sVertexFragmentBody = "<fragment uiName=\"depthShaderPluginInterpolantFragment\" name=\"depthShaderPluginInterpolantFragment\" type=\"interpolant\" class=\"ShadeFragment\" version=\"1.0\">" " <description><![CDATA[Depth shader vertex fragment]]></description>" " <properties>" " <float3 name=\"Pm\" semantic=\"Pm\" flags=\"varyingInputParam\" />" " <float4x4 name=\"worldViewProj\" semantic=\"worldviewprojection\" />" " </properties>" " <values>" " </values>" " <outputs>" " <float name=\"outDepthValue\" ^1s/>" " </outputs>" " <implementation>" " <implementation render=\"OGSRenderer\" language=\"Cg\" lang_version=\"2.1\">" " <function_name val=\"depthShaderPluginInterpolantFragment\" />" " <source><![CDATA[" "float depthShaderPluginInterpolantFragment(float depthValue) \n" "{ \n" " return depthValue; \n" "} \n]]>" " </source>" " <vertex_source><![CDATA[" "float idepthShaderPluginInterpolantFragment(float3 Pm, float4x4 worldViewProj) \n" "{ \n" " float4 pCamera = mul(worldViewProj, float4(Pm, 1.0f)); \n" " return (pCamera.z - pCamera.w*2.0f); \n" "} \n]]>" " </vertex_source>" " </implementation>" " <implementation render=\"OGSRenderer\" language=\"HLSL\" lang_version=\"11.0\">" " <function_name val=\"depthShaderPluginInterpolantFragment\" />" " <source><![CDATA[" "float depthShaderPluginInterpolantFragment(float depthValue) \n" "{ \n" " return depthValue; \n" "} \n]]>" " </source>" " <vertex_source><![CDATA[" "float idepthShaderPluginInterpolantFragment(float3 Pm, float4x4 worldViewProj) \n" "{ \n" " float4 pCamera = mul(float4(Pm, 1.0f), worldViewProj); \n" " return (pCamera.z - pCamera.w*2.0f); \n" "} \n]]>" " </vertex_source>" " </implementation>" " <implementation render=\"OGSRenderer\" language=\"GLSL\" lang_version=\"3.0\">" " <function_name val=\"depthShaderPluginInterpolantFragment\" />" " <source><![CDATA[" "float depthShaderPluginInterpolantFragment(float depthValue) \n" "{ \n" " return depthValue; \n" "} \n]]>" " </source>" " <vertex_source><![CDATA[" "float idepthShaderPluginInterpolantFragment(vec3 Pm, mat4 worldViewProj) \n" "{ \n" " vec4 pCamera = worldViewProj * vec4(Pm, 1.0f); \n" " return (pCamera.z - pCamera.w*2.0f); \n" "} \n]]>" " </vertex_source>" " </implementation>" " </implementation>" "</fragment>"; static const MString sFragmentGraphName("depthShaderPluginGraph"); static const char* sFragmentGraphBody = "<fragment_graph name=\"depthShaderPluginGraph\" ref=\"depthShaderPluginGraph\" class=\"FragmentGraph\" version=\"1.0\">" " <fragments>" " <fragment_ref name=\"depthShaderPluginFragment\" ref=\"depthShaderPluginFragment\" />" " <fragment_ref name=\"depthShaderPluginInterpolantFragment\" ref=\"depthShaderPluginInterpolantFragment\" />" " </fragments>" " <connections>" " <connect from=\"depthShaderPluginInterpolantFragment.outDepthValue\" to=\"depthShaderPluginFragment.depthValue\" />" " </connections>" " <properties>" " <float3 name=\"Pm\" ref=\"depthShaderPluginInterpolantFragment.Pm\" semantic=\"Pm\" flags=\"varyingInputParam\" />" " <float4x4 name=\"worldViewProj\" ref=\"depthShaderPluginInterpolantFragment.worldViewProj\" semantic=\"worldviewprojection\" />" " <float3 name=\"color\" ref=\"depthShaderPluginFragment.color\" />" " <float3 name=\"colorFar\" ref=\"depthShaderPluginFragment.colorFar\" />" " <float name=\"near\" ref=\"depthShaderPluginFragment.near\" />" " <float name=\"far\" ref=\"depthShaderPluginFragment.far\" />" " </properties>" " <values>" " <float3 name=\"color\" value=\"0.0,1.0,0.0\" />" " <float3 name=\"colorFar\" value=\"0.0,0.0,1.0\" />" " <float name=\"near\" value=\"0.0\" />" " <float name=\"far\" value=\"2.0\" />" " </values>" " <outputs>" " <float3 name=\"outColor\" ref=\"depthShaderPluginFragment.outColor\" />" " </outputs>" "</fragment_graph>"; // Register fragments with the manager if needed MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer(); if (theRenderer) { MHWRender::MFragmentManager* fragmentMgr = theRenderer->getFragmentManager(); if (fragmentMgr) { // Add fragments if needed bool fragAdded = fragmentMgr->hasFragment(sFragmentName); bool vertFragAdded = fragmentMgr->hasFragment(sVertexFragmentName); bool graphAdded = fragmentMgr->hasFragment(sFragmentGraphName); if (!fragAdded) { fragAdded = (sFragmentName == fragmentMgr->addShadeFragmentFromBuffer(sFragmentBody, false)); } if (!vertFragAdded) { // In DirectX, need to specify a semantic for the output of the vertex shader MString vertBody; if (theRenderer->drawAPI() == MHWRender::kDirectX11) { vertBody.format(MString(sVertexFragmentBody), MString("semantic=\"extraDepth\" ")); } else { vertBody.format(MString(sVertexFragmentBody), MString(" ")); } vertFragAdded = (sVertexFragmentName == fragmentMgr->addShadeFragmentFromBuffer(vertBody.asChar(), false)); } if (!graphAdded) { graphAdded = (sFragmentGraphName == fragmentMgr->addFragmentGraphFromBuffer(sFragmentGraphBody)); } // If we have them all, use the final graph for the override if (fragAdded && vertFragAdded && graphAdded) { fFragmentName = sFragmentGraphName; } } } }
MStatus atomImport::reader( const MFileObject& file, const MString& options, FileAccessMode mode) { MStatus status = MS::kFailure; MString fileName = file.fullName(); #if defined (OSMac_) char fname[MAXPATHLEN]; strcpy (fname, fileName.asChar()); ifstream animFile(fname); #else ifstream animFile(fileName.asChar()); #endif // Parse the options. The options syntax is in the form of // "flag=val;flag1=val;flag2=val" // if(animFile.good()==false) return status; MString pasteFlags; MString prefix; MString suffix; MString search; MString replace; MString mapFile; bool replaceLayers = false; MString exportEditsFile; bool includeChildren = false; atomNodeNameReplacer::ReplaceType type = atomNodeNameReplacer::eHierarchy; MString templateName; MString viewName; bool useTemplate = false; if (options.length() > 0) { // Set up the flags for the paste command. // const MString flagSrcTime("srcTime"); const MString flagDstTime("dstTime"); const MString flagOldDstTime("time"); const MString flagCopies("copies"); const MString flagOption("option"); const MString flagConnect("connect"); const MString flagMatch("match"); const MString flagSearch("search"); const MString flagReplace("replace"); const MString flagPrefix("prefix"); const MString flagSuffix("suffix"); const MString flagMapFile("mapFile"); const MString flagHierarchy("hierarchy"); const MString flagString("string"); const MString flagSelected("selected"); const MString flagTemplate("template"); const MString flagView("view"); const MString optionChildrenToo("childrenToo"); const MString optionTemplate("template"); const MString flagExportEdits("exportEdits"); MString copyValue; MString flagValue; MString connectValue; MString match; MString srcTimeValue; MString dstTimeValue; // Start parsing. // MStringArray optionList; MStringArray theOption; options.split(';', optionList); unsigned nOptions = optionList.length(); for (unsigned i = 0; i < nOptions; i++) { theOption.clear(); optionList[i].split('=', theOption); if (theOption.length() < 1) { continue; } if (theOption[0] == flagCopies && theOption.length() > 1) { copyValue = theOption[1];; } else if (theOption[0] == flagOption && theOption.length() > 1) { flagValue = theOption[1]; } else if (theOption[0] == flagConnect && theOption.length() > 1) { if (theOption[1].asInt() != 0) { connectValue += theOption[1]; } } else if( theOption[0] == flagTemplate && theOption.length() > 1) { templateName = theOption[1]; } else if( theOption[0] == flagView && theOption.length() > 1) { viewName = theOption[1]; } else if (theOption[0] == flagSrcTime && theOption.length() > 1) { srcTimeValue += theOption[1]; } else if ((theOption[0] == flagDstTime || theOption[0] == flagOldDstTime )&& theOption.length() > 1) { dstTimeValue += theOption[1]; } else if (theOption[0] == flagMatch && theOption.length() > 1) { match = theOption[1]; } else if (theOption[0] == flagSearch && theOption.length() > 1) { search = theOption[1]; } else if (theOption[0] == flagReplace && theOption.length() > 1) { replace = theOption[1]; } else if (theOption[0] == flagPrefix && theOption.length() > 1) { prefix = theOption[1]; } else if (theOption[0] == flagSuffix && theOption.length() > 1) { suffix = theOption[1]; } else if (theOption[0] == flagMapFile && theOption.length() > 1) { mapFile = theOption[1]; } else if (theOption[0] == flagSelected && theOption.length() > 1) { includeChildren = (theOption[1] == optionChildrenToo) ? true : false; if(theOption[1] == optionTemplate) useTemplate = true; } else if (theOption[0] == flagExportEdits && theOption.length() > 1) { exportEditsFile = theOption[1]; } } if (copyValue.length() > 0) { pasteFlags += " -copies "; pasteFlags += copyValue; pasteFlags += " "; } if (flagValue.length() > 0) { pasteFlags += " -option \""; pasteFlags += flagValue; pasteFlags += "\" "; if(flagValue == MString("replace")) replaceLayers = true; } if (connectValue.length() > 0) { pasteFlags += " -connect "; pasteFlags += connectValue; pasteFlags += " "; } if (dstTimeValue.length() > 0) { bool useQuotes = !dstTimeValue.isDouble(); pasteFlags += " -time "; if (useQuotes) pasteFlags += "\""; pasteFlags += dstTimeValue; if (useQuotes) pasteFlags += "\""; pasteFlags += " "; } if (srcTimeValue.length() > 0) { MTime lClipStartTime; MTime lClipEndTime; MStringArray lTimes; if ( MStatus::kSuccess == srcTimeValue.split( L':', lTimes ) ) { if ( lTimes.length() > 0 ) { double lImportStartFrame = lTimes[0].asDouble(); double lImportEndFrame = lImportStartFrame; if ( lTimes.length() > 1 ) { lImportEndFrame = lTimes[1].asDouble(); } fReader.setImportFrameRange( lImportStartFrame, lImportEndFrame ); } else { fReader.clearImportFrameRange(); } } } else { fReader.clearImportFrameRange(); } if(match.length() >0) { if(match == flagHierarchy) type = atomNodeNameReplacer::eHierarchy; else if(match == flagString) type = atomNodeNameReplacer::eSearchReplace; else if(match == flagMapFile) type = atomNodeNameReplacer::eMapFile; } //not set, then we leave what we had } // If the selection list is empty, there is nothing to import. // MSelectionList sList; std::vector<unsigned int> depths; atomTemplateReader templateReader; if(useTemplate == true) { templateReader.setTemplate(templateName,viewName); includeChildren = false; templateReader.selectNodes(); //make the selection set be us. } SelectionGetter::getSelectedObjects(includeChildren,sList,depths); if (sList.isEmpty()) { MString msg = MStringResource::getString(kNothingSelected, status); MGlobal::displayError(msg); return (MS::kFailure); } atomNodeNameReplacer replacer(type,sList,depths,prefix,suffix,search,replace,mapFile); if (mode == kImportAccessMode) { status = importAnim(sList,animFile,pasteFlags,replacer,exportEditsFile,templateReader,replaceLayers); } animFile.close(); return status; }
//----------------------------------------------------------------------------- // Purpose: Export the specified bits of the maya scene into the specified file // Input : mArgDatabase The command line arguments as passed // Output : MS::kSuccess if ok, MS::kFailure otherwise //----------------------------------------------------------------------------- MStatus CVstSmdIOCmd::DoImport( const MArgDatabase &mArgDatabase ) { MString optFilename; if ( mArgDatabase.getFlagArgument( kOptFilename, 0, optFilename ) != MS::kSuccess || optFilename.length() == 0 ) { MGlobal::displayError( "No filename specified for import" ); return MS::kFailure; } MString optGame; if ( mArgDatabase.isFlagSet( kOptGame ) ) { mArgDatabase.getFlagArgument( kOptGame, 0, optGame ); } MString optTextureArchive; if ( mArgDatabase.isFlagSet( kOptTextureArchive ) ) { mArgDatabase.getFlagArgument( kOptTextureArchive, 0, optTextureArchive ); } CQcData qcData; char fullPath[ MAX_PATH ]; if ( !_fullpath( fullPath, optFilename.asChar(), sizeof( fullPath ) ) ) { strncpy( fullPath, optFilename.asChar(), sizeof( fullPath ) ); } qcData.GetQcData( fullPath ); if ( mArgDatabase.isFlagSet( kOptUpAxis ) ) { MString upAxis; mArgDatabase.getFlagArgument( kOptUpAxis, 0, upAxis ); switch ( *upAxis.asChar() ) { case 'x': case 'X': qcData.m_upAxis = 0; break; case 'y': case 'Y': qcData.m_upAxis = 1; break; case 'z': case 'Z': default: qcData.m_upAxis = 2; break; } } CSmdImport smdImport( optGame.asChar(), optTextureArchive.asChar() ); if ( mArgDatabase.isFlagSet( kOptImportSkeleton ) && !mArgDatabase.isFlagSet( kOptVmf ) ) { mArgDatabase.getFlagArgument( kOptImportSkeleton, 0, smdImport.m_optImportSkeleton ); } smdImport.SetNodeAddPrefix( GetNodeAddPrefix( mArgDatabase ) ); smdImport.SetNodeDelPrefix( GetNodeDelPrefix( mArgDatabase ) ); if ( mArgDatabase.isFlagSet( kOptImportType ) ) { MString optImportType; if ( mArgDatabase.getFlagArgument( kOptImportType, 0, optImportType ) && ( *optImportType.asChar() == 'a' || *optImportType.asChar() == 'A' || *optImportType.asChar() == 's' || *optImportType.asChar() == 'S' ) ) { MSelectionList mSelectionList; mArgDatabase.getObjects( mSelectionList ); MDagPath rootDagPath; if ( mSelectionList.length() && mSelectionList.getDagPath( 0, rootDagPath ) ) { return smdImport.ImportAnimation( optFilename.asChar(), rootDagPath, qcData, m_undo ); } else { merr << "Cannot import animation without the root of the skeleton is selected or specified" << std::endl; return MS::kFailure; } } } MTransformationMatrix topLevel; if ( mArgDatabase.isFlagSet( kOptOrigin ) ) { MVector o; mArgDatabase.getFlagArgument( kOptOrigin, 0, o.x ); mArgDatabase.getFlagArgument( kOptOrigin, 1, o.y ); mArgDatabase.getFlagArgument( kOptOrigin, 2, o.z ); topLevel.setTranslation( o, MSpace::kObject ); } if ( mArgDatabase.isFlagSet( kOptAngles ) ) { MVector a; if ( mArgDatabase.isFlagSet( kOptVmf ) ) { // The angles are specified in Yaw Pitch Roll order ( YZX ) // but they're still an XYZ rotation mArgDatabase.getFlagArgument( kOptAngles, 0, a.y ); mArgDatabase.getFlagArgument( kOptAngles, 1, a.z ); mArgDatabase.getFlagArgument( kOptAngles, 2, a.x ); } else { mArgDatabase.getFlagArgument( kOptAngles, 0, a.x ); mArgDatabase.getFlagArgument( kOptAngles, 1, a.y ); mArgDatabase.getFlagArgument( kOptAngles, 2, a.z ); } const MEulerRotation e( a.x / 180.0 * M_PI, a.y / 180.0 * M_PI, a.z / 180.0 * M_PI, MEulerRotation::kXYZ ); topLevel.rotateBy( e.asQuaternion(), MSpace::kObject ); } if ( mArgDatabase.isFlagSet( kOptVmf ) ) { if ( qcData.m_upAxis == 1U ) { topLevel.rotateBy( MEulerRotation( 90.0 / 180.0 * M_PI, 0.0, 90.0 / 180.0 * M_PI ).asQuaternion(), MSpace::kObject ); } else { topLevel.rotateBy( MEulerRotation( 0.0, 0.0, 90.0 / 180.0 * M_PI ).asQuaternion(), MSpace::kObject ); } } else { switch ( qcData.m_upAxis ) { case 0U: // X Up if ( MGlobal::isYAxisUp() ) { topLevel.rotateBy( MEulerRotation( -M_PI / 2.0, M_PI / 2.0, 0.0 ).asQuaternion(), MSpace::kObject ); } else { topLevel.rotateBy( MEulerRotation( 0.0, M_PI / 2.0, 0.0 ).asQuaternion(), MSpace::kObject ); } break; case 1U: // Y Up if ( MGlobal::isZAxisUp() ) { topLevel.rotateBy( MEulerRotation( M_PI / 2.0, 0.0, 0.0 ).asQuaternion(), MSpace::kObject ); } break; default: case 2U: // Z Up if ( MGlobal::isYAxisUp() ) { topLevel.rotateBy( MEulerRotation( -M_PI / 2.0, 0.0, 0.0 ).asQuaternion(), MSpace::kObject ); } break; } } MDagPath mDagPath( smdImport.DoIt( optFilename.asChar(), qcData, topLevel, m_undo ) ); if ( mDagPath.isValid() && mDagPath.length() ) { if ( mArgDatabase.isFlagSet( kOptVmf ) ) { MFnNumericAttribute nFn; MObject aObj( nFn.create( "yUp", "yUp", MFnNumericData::kBoolean, false ) ); MDagPath sDagPath( mDagPath ); sDagPath.extendToShapeDirectlyBelow( 0 ); m_undo.DagModifier().addAttribute( sDagPath.node(), aObj ); m_undo.DagModifierDoIt(); MPlug aP( sDagPath.node(), aObj ); if ( qcData.m_upAxis == 1U ) { aP.setValue( true ); } else { aP.setValue( false ); } } m_undo.SaveCurrentSelection(); MGlobal::select( mDagPath, MObject::kNullObj, MGlobal::kReplaceList ); setResult( mDagPath.partialPathName() ); m_undo.SaveCurrentSelection(); return MS::kSuccess; } m_undo.Undo(); return MS::kFailure; }
/** Create a RIB compatible representation of a Maya polygon mesh. */ liqRibMeshData::liqRibMeshData( MObject mesh ) : numFaces( 0 ), numPoints ( 0 ), numNormals ( 0 ), nverts(), verts(), vertexParam(NULL), normalParam(NULL) { CM_TRACE_FUNC("liqRibMeshData::liqRibMeshData("<<MFnDagNode(mesh).fullPathName().asChar()<<")"); unsigned int i; unsigned int j; areaLight = false; LIQDEBUGPRINTF( "-> creating mesh\n" ); MFnMesh fnMesh( mesh ); objDagPath = fnMesh.dagPath(); MStatus astatus; name = fnMesh.name(); areaLight =( liquidGetPlugValue( fnMesh, "areaIntensity", areaIntensity, astatus ) == MS::kSuccess )? true : false ; if ( areaLight ) { MDagPath meshDagPath; meshDagPath = fnMesh.dagPath(); MTransformationMatrix worldMatrix = meshDagPath.inclusiveMatrix(); MMatrix worldMatrixM = worldMatrix.asMatrix(); worldMatrixM.get( transformationMatrix ); } numPoints = fnMesh.numVertices(); numNormals = fnMesh.numNormals(); // UV sets ------------------- // //const unsigned numSTs( fnMesh.numUVs() ); const unsigned numUVSets( fnMesh.numUVSets() ); MString currentUVSetName; MStringArray extraUVSetNames; fnMesh.getCurrentUVSetName( currentUVSetName ); { MStringArray UVSetNames; fnMesh.getUVSetNames( UVSetNames ); for ( unsigned i( 0 ); i<numUVSets; i++ ) if ( UVSetNames[i] != currentUVSetName ) extraUVSetNames.append( UVSetNames[i] ); } numFaces = fnMesh.numPolygons(); const unsigned numFaceVertices( fnMesh.numFaceVertices() ); if ( numPoints < 1 ) { // MGlobal::displayInfo( MString( "fnMesh: " ) + fnMesh.name() ); // cerr << "Liquid : Could not export degenerate mesh '"<< fnMesh.fullPathName( &astatus ).asChar() << "'" << endl << flush; return; } unsigned face = 0; unsigned faceVertex = 0; unsigned count; unsigned vertex; unsigned normal; float S; float T; MPoint point; liqTokenPointer pointsPointerPair; liqTokenPointer normalsPointerPair; liqTokenPointer pFaceVertexSPointer; liqTokenPointer pFaceVertexTPointer; // Allocate memory and tokens numFaces = numFaces; nverts = shared_array< liqInt >( new liqInt[ numFaces ] ); verts = shared_array< liqInt >( new liqInt[ numFaceVertices ] ); pointsPointerPair.set( "P", rPoint, numPoints ); pointsPointerPair.setDetailType( rVertex ); if ( numNormals == numPoints ) { normalsPointerPair.set( "N", rNormal, numPoints ); normalsPointerPair.setDetailType( rVertex ); } else { normalsPointerPair.set( "N", rNormal, numFaceVertices ); normalsPointerPair.setDetailType( rFaceVarying ); } // uv std::vector<liqTokenPointer> UVSetsArray; UVSetsArray.reserve( 1 + extraUVSetNames.length() ); liqTokenPointer currentUVSetUPtr; liqTokenPointer currentUVSetVPtr; liqTokenPointer currentUVSetNamePtr; liqTokenPointer extraUVSetsUPtr; liqTokenPointer extraUVSetsVPtr; liqTokenPointer extraUVSetsNamePtr; if(liqglo.liqglo_outputMeshAsRMSArrays) { currentUVSetUPtr.set( "s", rFloat, numFaceVertices ); currentUVSetUPtr.setDetailType( rFaceVarying ); currentUVSetVPtr.set( "t", rFloat, numFaceVertices ); currentUVSetVPtr.setDetailType( rFaceVarying ); currentUVSetNamePtr.set( "currentUVSet", rString, 1 ); currentUVSetNamePtr.setDetailType( rConstant ); if( numUVSets > 1 ) { extraUVSetsUPtr.set( "u_uvSet", rFloat, numFaceVertices, numUVSets-1 ); extraUVSetsUPtr.setDetailType( rFaceVarying ); extraUVSetsVPtr.set( "v_uvSet", rFloat, numFaceVertices, numUVSets-1 ); extraUVSetsVPtr.setDetailType( rFaceVarying ); extraUVSetsNamePtr.set( "extraUVSets", rString, numUVSets-1 ); extraUVSetsNamePtr.setDetailType( rConstant ); } } else { if ( numUVSets > 0 ) { liqTokenPointer pFaceVertexPointerPair; pFaceVertexPointerPair.set( "st", rFloat, numFaceVertices, 2 ); pFaceVertexPointerPair.setDetailType( rFaceVarying ); UVSetsArray.push_back( pFaceVertexPointerPair ); for ( unsigned j( 0 ); j<extraUVSetNames.length(); j++) { liqTokenPointer pFaceVertexPointerPair; pFaceVertexPointerPair.set( extraUVSetNames[j].asChar(), rFloat, numFaceVertices, 2 ); pFaceVertexPointerPair.setDetailType( rFaceVarying ); UVSetsArray.push_back( pFaceVertexPointerPair ); } if( liqglo.liqglo_outputMeshUVs ) { // Match MTOR, which also outputs face-varying STs as well for some reason - Paul // not anymore - Philippe pFaceVertexSPointer.set( "u", rFloat, numFaceVertices ); pFaceVertexSPointer.setDetailType( rFaceVarying ); pFaceVertexTPointer.set( "v", rFloat, numFaceVertices ); pFaceVertexTPointer.setDetailType( rFaceVarying ); } } } vertexParam = pointsPointerPair.getTokenFloatArray(); normalParam = normalsPointerPair.getTokenFloatArray(); // Read the mesh from Maya MFloatVectorArray normals; fnMesh.getNormals( normals ); for ( MItMeshPolygon polyIt ( mesh ); polyIt.isDone() == false; polyIt.next() ) { count = polyIt.polygonVertexCount(); nverts[face] = count; for( i=0; i<count; i++ ) // boucle sur les vertex de la face { vertex = polyIt.vertexIndex( i ); verts[faceVertex] = vertex; point = polyIt.point( i, MSpace::kObject ); pointsPointerPair.setTokenFloat( vertex, point.x, point.y, point.z ); normal = polyIt.normalIndex( i ); if( numNormals == numPoints ) normalsPointerPair.setTokenFloat( vertex, normals[normal].x, normals[normal].y, normals[normal].z ); else normalsPointerPair.setTokenFloat( faceVertex, normals[normal].x, normals[normal].y, normals[normal].z ); if( liqglo.liqglo_outputMeshAsRMSArrays ) { for( j=0; j<numUVSets; j++ ) { if(j==0) { MString uvSetName = currentUVSetName; // set uvSet name currentUVSetNamePtr.setTokenString( 0, currentUVSetName.asChar() ); // set uv values fnMesh.getPolygonUV( face, i, S, T, &uvSetName ); currentUVSetUPtr.setTokenFloat( faceVertex, S ); currentUVSetVPtr.setTokenFloat( faceVertex, 1-T ); } else { MString uvSetName = extraUVSetNames[j-1]; // set uvSet name extraUVSetsNamePtr.setTokenString( j-1, extraUVSetNames[j-1].asChar() ); // set uv values fnMesh.getPolygonUV( face, i, S, T, &uvSetName ); extraUVSetsUPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, S ); extraUVSetsVPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, 1-T ); } } } else { if ( numUVSets ) { for( j=0; j<numUVSets; j++ ) { MString uvSetName; if(j==0) { uvSetName = currentUVSetName; } else { uvSetName = extraUVSetNames[j-1]; } fnMesh.getPolygonUV( face, i, S, T, &uvSetName ); UVSetsArray[j].setTokenFloat( faceVertex, 0, S ); UVSetsArray[j].setTokenFloat( faceVertex, 1, 1-T ); //printf("V%d %s : %f %f => %f %f \n", i, uvSetName.asChar(), S, T, S, 1-T); if( liqglo.liqglo_outputMeshUVs && j==0) { // Match MTOR, which always outputs face-varying STs as well for some reason - Paul pFaceVertexSPointer.setTokenFloat( faceVertex, S ); pFaceVertexTPointer.setTokenFloat( faceVertex, 1-T ); } } } } // printf( "[%d] faceVertex = %d vertex = %d\n", i, faceVertex, vertex ); ++faceVertex; } ++face; } // Add tokens to array and clean up after tokenPointerArray.push_back( pointsPointerPair ); tokenPointerArray.push_back( normalsPointerPair ); if(liqglo.liqglo_outputMeshAsRMSArrays) { tokenPointerArray.push_back( currentUVSetNamePtr ); tokenPointerArray.push_back( currentUVSetUPtr ); tokenPointerArray.push_back( currentUVSetVPtr ); if( numUVSets > 1 ) { tokenPointerArray.push_back( extraUVSetsNamePtr ); tokenPointerArray.push_back( extraUVSetsUPtr ); tokenPointerArray.push_back( extraUVSetsVPtr ); } } else { if( UVSetsArray.size() ) tokenPointerArray.insert( tokenPointerArray.end(), UVSetsArray.begin(), UVSetsArray.end() ); if( liqglo.liqglo_outputMeshUVs ) { tokenPointerArray.push_back( pFaceVertexSPointer ); tokenPointerArray.push_back( pFaceVertexTPointer ); } } addAdditionalSurfaceParameters( mesh ); }
/* * get maya poly mesh data */ bool liqRibMeshData::getMayaData( MObject mesh, bool useNormals ) { bool ret = true; // LIQDEBUGPRINTF( "-> mesh getMayaData (useNormals = %s )\n", ( ( useNormals )? "Yes" : "No" ) ); MFnMesh fnMesh( mesh ); objDagPath = fnMesh.dagPath(); MStatus astatus; name = fnMesh.name(); longName = fnMesh.fullPathName(); numPoints = fnMesh.numVertices(); numFaces = fnMesh.numPolygons(); if ( useNormals ) numNormals = fnMesh.numNormals(); if ( numPoints < 1 ) { liquidMessage( "Could not export degenerate mesh " + longName, messageInfo ); return false; } // UV sets ------------------- // //const unsigned numSTs( fnMesh.numUVs() ); const unsigned numUVSets( fnMesh.numUVSets() ); MString currentUVSetName; fnMesh.getCurrentUVSetName( currentUVSetName ); MStringArray extraUVSetNames; MStringArray UVSetNames; fnMesh.getUVSetNames( UVSetNames ); for ( unsigned i( 0 ); i < numUVSets ; i++ ) if ( UVSetNames[i] != currentUVSetName ) extraUVSetNames.append( UVSetNames[i] ); const unsigned numFaceVertices( fnMesh.numFaceVertices() ); unsigned face ( 0 ); unsigned faceVertex ( 0 ); unsigned count; unsigned vertex; unsigned normal; float S; float T; MPoint point; liqTokenPointer pointsPointerPair; liqTokenPointer normalsPointerPair; liqTokenPointer pFaceVertexSPointer; liqTokenPointer pFaceVertexTPointer; // Allocate memory and tokens nverts = shared_array< RtInt >( new RtInt[ numFaces ] ); verts = shared_array< RtInt >( new RtInt[ numFaceVertices ] ); pointsPointerPair.set( "P", rPoint, numPoints ); pointsPointerPair.setDetailType( rVertex ); if ( useNormals ) { if ( numNormals == numPoints ) { normalsPointerPair.set( "N", rNormal, numPoints ); normalsPointerPair.setDetailType( rVertex ); } else { normalsPointerPair.set( "N", rNormal, numFaceVertices ); normalsPointerPair.setDetailType( rFaceVarying ); } } // uv std::vector<liqTokenPointer> UVSetsArray; UVSetsArray.reserve( 1 + extraUVSetNames.length() ); liqTokenPointer currentUVSetUPtr; liqTokenPointer currentUVSetVPtr; liqTokenPointer currentUVSetNamePtr; liqTokenPointer extraUVSetsUPtr; liqTokenPointer extraUVSetsVPtr; liqTokenPointer extraUVSetsNamePtr; if ( liqglo_outputMeshAsRMSArrays ) { currentUVSetUPtr.set( "s", rFloat, numFaceVertices ); currentUVSetUPtr.setDetailType( rFaceVarying ); currentUVSetVPtr.set( "t", rFloat, numFaceVertices ); currentUVSetVPtr.setDetailType( rFaceVarying ); currentUVSetNamePtr.set( "currentUVSet", rString, 1 ); currentUVSetNamePtr.setDetailType( rConstant ); if ( numUVSets > 1 ) { extraUVSetsUPtr.set( "u_uvSet", rFloat, numFaceVertices, numUVSets-1 ); extraUVSetsUPtr.setDetailType( rFaceVarying ); extraUVSetsVPtr.set( "v_uvSet", rFloat, numFaceVertices, numUVSets-1 ); extraUVSetsVPtr.setDetailType( rFaceVarying ); extraUVSetsNamePtr.set( "extraUVSets", rString, numUVSets-1 ); extraUVSetsNamePtr.setDetailType( rConstant ); } } else { if ( numUVSets > 0 ) { liqTokenPointer pFaceVertexPointerPair; pFaceVertexPointerPair.set( "st", rFloat, numFaceVertices, 2 ); pFaceVertexPointerPair.setDetailType( rFaceVarying ); UVSetsArray.push_back( pFaceVertexPointerPair ); for ( unsigned j( 0 ); j < extraUVSetNames.length() ; j++ ) { liqTokenPointer pFaceVertexPointerPair; pFaceVertexPointerPair.set( extraUVSetNames[j].asChar(), rFloat, numFaceVertices, 2 ); pFaceVertexPointerPair.setDetailType( rFaceVarying ); UVSetsArray.push_back( pFaceVertexPointerPair ); } if ( liqglo_outputMeshUVs ) { // Match MTOR, which also outputs face-varying STs as well for some reason - Paul // not anymore - Philippe pFaceVertexSPointer.set( "u", rFloat, numFaceVertices ); pFaceVertexSPointer.setDetailType( rFaceVarying ); pFaceVertexTPointer.set( "v", rFloat, numFaceVertices ); pFaceVertexTPointer.setDetailType( rFaceVarying ); } } } vertexParam = pointsPointerPair.getTokenFloatArray(); MFloatVectorArray normals; // Read the mesh normals from Maya if ( useNormals ) { normalParam = normalsPointerPair.getTokenFloatArray(); fnMesh.getNormals( normals ); } for ( MItMeshPolygon polyIt ( mesh ); polyIt.isDone() == false ; polyIt.next() ) { count = polyIt.polygonVertexCount(); nverts[face] = count; unsigned j, i = count; // printf("poly count = %d\n", count ); while ( i ) { --i; vertex = polyIt.vertexIndex( i ); verts[faceVertex] = vertex; point = polyIt.point( i, MSpace::kObject ); pointsPointerPair.setTokenFloat( vertex, point.x, point.y, point.z ); if ( useNormals ) { normal = polyIt.normalIndex( i ); if ( numNormals == numPoints ) normalsPointerPair.setTokenFloat( vertex, normals[normal].x, normals[normal].y, normals[normal].z ); else normalsPointerPair.setTokenFloat( faceVertex, normals[normal].x, normals[normal].y, normals[normal].z ); } if ( liqglo_outputMeshAsRMSArrays ) { for ( j = 0 ; j < numUVSets ; j++ ) { if ( j == 0) { MString uvSetName = currentUVSetName; // set uvSet name currentUVSetNamePtr.setTokenString( 0, currentUVSetName.asChar() ); // set uv values fnMesh.getPolygonUV( face, i, S, T, &uvSetName ); currentUVSetUPtr.setTokenFloat( faceVertex, S ); currentUVSetVPtr.setTokenFloat( faceVertex, 1-T ); } else { MString uvSetName = extraUVSetNames[j-1]; // set uvSet name extraUVSetsNamePtr.setTokenString( j-1, extraUVSetNames[j-1].asChar() ); // set uv values fnMesh.getPolygonUV( face, i, S, T, &uvSetName ); extraUVSetsUPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, S ); extraUVSetsVPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, 1-T ); } } } else { if ( numUVSets ) { for( j = 0; j < numUVSets; j++ ) { MString uvSetName = ( j == 0 )? currentUVSetName: extraUVSetNames[ j - 1 ] ; fnMesh.getPolygonUV( face, i, S, T, &uvSetName ); UVSetsArray[j].setTokenFloat( faceVertex, 0, S ); UVSetsArray[j].setTokenFloat( faceVertex, 1, 1 - T ); //printf("V%d %s : %f %f => %f %f \n", i, uvSetName.asChar(), S, T, S, 1-T); if ( liqglo_outputMeshUVs && j==0) { // Match MTOR, which always outputs face-varying STs as well for some reason - Paul pFaceVertexSPointer.setTokenFloat( faceVertex, S ); pFaceVertexTPointer.setTokenFloat( faceVertex, 1 - T ); } } } } ++faceVertex; } ++face; } // Add tokens to array and clean up after tokenPointerArray.push_back( pointsPointerPair ); if ( useNormals ) tokenPointerArray.push_back( normalsPointerPair ); if ( liqglo_outputMeshAsRMSArrays ) { tokenPointerArray.push_back( currentUVSetNamePtr ); tokenPointerArray.push_back( currentUVSetUPtr ); tokenPointerArray.push_back( currentUVSetVPtr ); if ( numUVSets > 1 ) { tokenPointerArray.push_back( extraUVSetsNamePtr ); tokenPointerArray.push_back( extraUVSetsUPtr ); tokenPointerArray.push_back( extraUVSetsVPtr ); } } else { if ( UVSetsArray.size() ) tokenPointerArray.insert( tokenPointerArray.end(), UVSetsArray.begin(), UVSetsArray.end() ); if ( liqglo_outputMeshUVs ) { tokenPointerArray.push_back( pFaceVertexSPointer ); tokenPointerArray.push_back( pFaceVertexTPointer ); } } return ret; }
int Renderer::preview( const std::string& fileName, const liqPreviewShaderOptions& options ) { CM_TRACE_FUNC("Renderer::preview("<<fileName<<","<<options.shaderNodeName<<")"); std::string shaderFileName; liqShader currentShader; MObject shaderObj; MString shader_type_TempForRefactoring;// [2/14/2012 yaoyansi] if ( options.fullShaderPath ) { // a full shader path was specified //cout <<"[liquid] got full path for preview !"<<endl; //shaderFileName = const_cast<char*>(options.shaderNodeName); std::string tmp( options.shaderNodeName ); currentShader.setShaderFileName(tmp.substr( 0, tmp.length() - 4 ) ); if ( options.type == "surface" ){ assert(0&&"we should use currentShader.shader_type_ex = \"surface\""); //currentShader.shader_type = SHADER_TYPE_SURFACE;// [2/14/2012 yaoyansi] shader_type_TempForRefactoring = "surface"; }else if ( options.type == "displacement" ){ assert(0&&"we should use currentShader.shader_type_ex = \"displacement\""); //currentShader.shader_type = SHADER_TYPE_DISPLACEMENT;// [2/14/2012 yaoyansi] shader_type_TempForRefactoring = "displacement"; } //cout <<"[liquid] options.shaderNodeName = " << options.shaderNodeName << endl; //cout <<"[liquid] options.type = "<<options.type<<endl; } else { // a shader node was specified MSelectionList shaderNameList; shaderNameList.add( options.shaderNodeName.c_str() ); shaderNameList.getDependNode( 0, shaderObj ); if( shaderObj == MObject::kNullObj ) { MGlobal::displayError( std::string( "Can't find node for " + options.shaderNodeName ).c_str() ); RiEnd(); return 0; } currentShader = liqShader( shaderObj ); shader_type_TempForRefactoring = currentShader.shader_type_ex; shaderFileName = currentShader.getShaderFileName(); } MFnDependencyNode assignedShader( shaderObj ); // Get the Pathes in globals node MObject globalObjNode; MString liquidShaderPath = "",liquidTexturePath = "",liquidProceduralPath = ""; MStatus status; MSelectionList globalList; // get the current project directory MString MELCommand = "workspace -q -rd"; MString MELReturn; MGlobal::executeCommand( MELCommand, MELReturn ); MString liquidProjectDir = MELReturn; status = globalList.add( "liquidGlobals" ); if ( globalList.length() > 0 ) { status.clear(); status = globalList.getDependNode( 0, globalObjNode ); MFnDependencyNode globalNode( globalObjNode ); liquidGetPlugValue( globalNode, "shaderPath", liquidShaderPath, status); liquidGetPlugValue( globalNode, "texturePath", liquidTexturePath, status); liquidGetPlugValue( globalNode, "proceduralPath", liquidProceduralPath, status); } if( fileName.empty() ) { RiBegin_liq( NULL ); #ifdef DELIGHT //RtPointer callBack( progressCallBack ); //RiOption( "statistics", "progresscallback", &callBack, RI_NULL ); #endif } else { liquidMessage2(messageInfo,"preview rib file: [%s]", fileName.c_str()); RiBegin_liq( (RtToken)fileName.c_str() ); } std::string liquidHomeDir = liquidSanitizeSearchPath( getEnvironment( "LIQUIDHOME" ) ); std::string shaderPath( "&:@:.:~:" + liquidHomeDir + "/lib/shaders" ); std::string texturePath( "&:@:.:~:" + liquidHomeDir + "/lib/textures" ); std::string proceduralPath( "&:@:.:~:" + liquidHomeDir + "/lib/shaders" ); std::string projectDir = std::string( liquidSanitizeSearchPath( liquidProjectDir ).asChar() ); if ( liquidProjectDir != "") { shaderPath += ":" + projectDir; texturePath += ":" + projectDir; proceduralPath += ":" + projectDir; } if ( liquidShaderPath != "" ) shaderPath += ":" + std::string( liquidSanitizeSearchPath( parseString( liquidShaderPath, false ) ).asChar()); if ( liquidTexturePath != "" ) texturePath += ":" + std::string( liquidSanitizeSearchPath( parseString( liquidTexturePath, false) ).asChar()); if ( liquidProceduralPath != "" ) proceduralPath += ":" + std::string( liquidSanitizeSearchPath( parseString( liquidProceduralPath, false) ).asChar()); RtString list( const_cast< RtString >( shaderPath.c_str() ) ); RiOption( "searchpath", "shader", &list, RI_NULL ); RtString texPath( const_cast< RtString >( texturePath.c_str() ) ); if( texPath[ 0 ] ) RiOption( "searchpath","texture", &texPath, RI_NULL ); RtString procPath( const_cast< RtString >( proceduralPath.c_str() ) ); if( procPath[ 0 ] ) RiOption( "searchpath","procedural", &procPath, RI_NULL ); RiShadingRate( ( RtFloat )options.shadingRate ); RiPixelSamples( options.pixelSamples, options.pixelSamples ); #ifdef PRMAN if ( MString( "PRMan" ) == liqglo.liquidRenderer.renderName ) RiPixelFilter( RiCatmullRomFilter, 4., 4. ); #elif defined( DELIGHT ) if ( MString( "3Delight" ) == liqglo.liquidRenderer.renderName ) RiPixelFilter( RiSeparableCatmullRomFilter, 4., 4. ); // RiPixelFilter( RiMitchellFilter, 4., 4.); #else RiPixelFilter( RiCatmullRomFilter, 4., 4. ); #endif RiFormat( ( RtInt )options.displaySize, ( RtInt )options.displaySize, 1.0 ); if( options.backPlane ) { RiDisplay( const_cast< RtString >( options.displayName.c_str() ), const_cast< RtString >( options.displayDriver.c_str() ), RI_RGB, RI_NULL ); } else { // Alpha might be useful RiDisplay( const_cast< RtString >( options.displayName.c_str() ), const_cast< RtString >( options.displayDriver.c_str() ), RI_RGBA, RI_NULL ); } RtFloat fov( 22.5 ); RiProjection( "perspective", "fov", &fov, RI_NULL ); RiTranslate( 0, 0, 2.75 ); RiExposure(1, currentShader.m_previewGamma); RtInt visible = 1; RtString transmission = "transparent"; RiAttribute( "visibility", ( RtToken ) "camera", &visible, RI_NULL ); RiAttribute( "visibility", ( RtToken ) "trace", &visible, RI_NULL ); // RiAttribute( "visibility", ( RtToken ) "transmission", ( RtPointer ) &transmission, RI_NULL ); RiWorldBegin(); RiReverseOrientation(); RiTransformBegin(); RiRotate( -90., 1., 0., 0. ); RiCoordinateSystem( "_environment" ); RiTransformEnd(); RtLightHandle ambientLightH, directionalLightH; RtFloat intensity; intensity = 0.05 * (RtFloat)options.previewIntensity; ambientLightH = RiLightSource( "ambientlight", "intensity", &intensity, RI_NULL ); intensity = 0.9 * (RtFloat)options.previewIntensity; RtPoint from; RtPoint to; from[0] = -1.; from[1] = 1.5; from[2] = -1.; to[0] = 0.; to[1] = 0.; to[2] = 0.; RiTransformBegin(); RiRotate( 55., 1, 0, 0 ); RiRotate( 30., 0, 1, 0 ); directionalLightH = RiLightSource( "liquiddistant", "intensity", &intensity, RI_NULL ); RiTransformEnd(); intensity = 0.2f * (RtFloat)options.previewIntensity; from[0] = 1.3f; from[1] = -1.2f; from[2] = -1.; RiTransformBegin(); RiRotate( -50., 1, 0, 0 ); RiRotate( -40., 0, 1, 0 ); directionalLightH = RiLightSource( "liquiddistant", "intensity", &intensity, RI_NULL ); RiTransformEnd(); RiAttributeBegin(); //ymesh omit this section, because liqShader::writeRibAttributes() do this work in that branch //I don't use liqShader::writeRibAttributes(), so I use this section. -yayansi float displacementBounds = 0.; liquidGetPlugValue( assignedShader, "displacementBound", displacementBounds, status); if ( displacementBounds > 0. ) { RtString coordsys = "shader"; RiArchiveRecord( RI_COMMENT, "ymesh omit this section, because liqShader::writeRibAttributes do this work in that branch" ); RiAttribute( "displacementbound", "coordinatesystem", &coordsys, RI_NULL ); RiAttribute( "displacementbound", "sphere", &displacementBounds, "coordinatesystem", &coordsys, RI_NULL ); } //LIQ_GET_SHADER_FILE_NAME( shaderFileName, options.shortShaderName, currentShader ); // output shader space MString shadingSpace; liquidGetPlugValue( assignedShader, "shaderSpace", shadingSpace, status); if ( shadingSpace != "" ) { RiTransformBegin(); RiCoordSysTransform( (char*) shadingSpace.asChar() ); } RiTransformBegin(); // Rotate shader space to make the preview more interesting RiRotate( 60., 1., 0., 0. ); RiRotate( 60., 0., 1., 0. ); RtFloat scale( 1.f / ( RtFloat )options.objectScale ); RiScale( scale, scale, scale ); if ( shader_type_TempForRefactoring=="surface" || shader_type_TempForRefactoring=="shader"/*currentShader.shader_type == SHADER_TYPE_SURFACE || currentShader.shader_type == SHADER_TYPE_SHADER */ ) // [2/14/2012 yaoyansi] { RiColor( currentShader.rmColor ); RiOpacity( currentShader.rmOpacity ); //cout << "Shader: " << shaderFileName << endl; if ( options.fullShaderPath ) RiSurface( (RtToken)shaderFileName.c_str(), RI_NULL ); else { liqShader liqAssignedShader( shaderObj ); liqAssignedShader.forceAs = SHADER_TYPE_SURFACE; liqAssignedShader.write(); } } else if ( shader_type_TempForRefactoring=="displacement"/*currentShader.shader_type == SHADER_TYPE_DISPLACEMENT*/ ) // [2/14/2012 yaoyansi] { RtToken Kd( "Kd" ); RtFloat KdValue( 1. ); #ifdef GENERIC_RIBLIB // !!! current ribLib has wrong interpretation of RiSurface parameters RiSurface( "plastic", Kd, &KdValue, RI_NULL ); #else RiSurface( "plastic", &Kd, &KdValue, RI_NULL ); #endif if ( options.fullShaderPath ) RiDisplacement( (RtToken)shaderFileName.c_str(), RI_NULL ); else { liqShader liqAssignedShader( shaderObj ); liqAssignedShader.forceAs = SHADER_TYPE_DISPLACEMENT; liqAssignedShader.write(); } } RiTransformEnd(); if ( shadingSpace != "" ) RiTransformEnd(); switch( options.primitiveType ) { case CYLINDER: { RiReverseOrientation(); RiScale( 0.95, 0.95, 0.95 ); RiRotate( 60., 1., 0., 0. ); RiTranslate( 0., 0., -0.05 ); RiCylinder( 0.5, -0.3, 0.3, 360., RI_NULL ); RiTranslate( 0., 0., 0.3f ); RiTorus( 0.485, 0.015, 0., 90., 360., RI_NULL ); RiDisk( 0.015, 0.485, 360., RI_NULL ); RiTranslate( 0., 0., -0.6 ); RiTorus( 0.485, 0.015, 270., 360., 360., RI_NULL ); RiReverseOrientation(); RiDisk( -0.015, 0.485, 360., RI_NULL ); break; } case TORUS: { RiRotate( 45., 1., 0., 0. ); RiTranslate( 0., 0., -0.05 ); RiReverseOrientation(); RiTorus( 0.3f, 0.2f, 0., 360., 360., RI_NULL ); break; } case PLANE: { RiScale( 0.5, 0.5, 0.5 ); RiReverseOrientation(); static RtPoint plane[4] = { { -1., 1., 0. }, { 1., 1., 0. }, { -1., -1., 0. }, { 1., -1., 0. } }; RiPatch( RI_BILINEAR, RI_P, (RtPointer) plane, RI_NULL ); break; } case TEAPOT: { RiTranslate( 0.06f, -0.18f, 0. ); RiRotate( -120., 1., 0., 0. ); RiRotate( 130., 0., 0., 1. ); RiScale( 0.2f, 0.2f, 0.2f ); RiArchiveRecord( RI_VERBATIM, "Geometry \"teapot\"" ); break; } case CUBE: { /* Lovely cube with rounded corners and edges */ RiScale( 0.35f, 0.35f, 0.35f ); RiRotate( 60., 1., 0., 0. ); RiRotate( 60., 0., 0., 1. ); RiTranslate( 0.11f, 0., -0.08f ); RiReverseOrientation(); static RtPoint top[ 4 ] = { { -0.95, 0.95, -1. }, { 0.95, 0.95, -1. }, { -0.95, -0.95, -1. }, { 0.95, -0.95, -1. } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) top, RI_NULL ); static RtPoint bottom[ 4 ] = { { 0.95, 0.95, 1. }, { -0.95, 0.95, 1. }, { 0.95, -0.95, 1. }, { -0.95, -0.95, 1. } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) bottom, RI_NULL ); static RtPoint right[ 4 ] = { { -0.95, -1., -0.95 }, { 0.95, -1., -0.95 }, { -0.95, -1., 0.95 }, { 0.95, -1., 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) right, RI_NULL ); static RtPoint left[ 4 ] = { { 0.95, 1., -0.95 }, { -0.95, 1., -0.95 }, { 0.95, 1., 0.95 }, { -0.95, 1., 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) left, RI_NULL ); static RtPoint front[ 4 ] = { {-1., 0.95, -0.95 }, { -1., -0.95, -0.95 }, { -1., 0.95, 0.95 }, { -1., -0.95, 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) front, RI_NULL ); static RtPoint back[ 4 ] = { { 1., -0.95, -0.95 }, { 1., 0.95, -0.95 }, { 1., -0.95, 0.95 }, { 1., 0.95, 0.95 } }; RiPatch( RI_BILINEAR, RI_P, ( RtPointer ) back, RI_NULL ); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0.95, 0. ); RiRotate( 90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, -0.95, 0. ); RiRotate( 180., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0., 0., 0.95 ); RiTransformBegin(); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiRotate( 180., 0., 0., 1. ); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, 0., 0.05, 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); RiRotate( 90., 1., 0., 0. ); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiRotate( 90., 0., 1., 0. ); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0., 0., -0.95 ); RiTransformBegin(); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiRotate( 180., 0., 0., 1. ); RiTransformBegin(); RiTranslate( 0.95, 0.95, 0. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, -0.95, 0. ); RiRotate( -90., 0., 0., 1. ); RiSphere( 0.05, -0.05, 0., 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); RiRotate( 90., 1., 0., 0. ); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 180., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiRotate( -90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiRotate( 90., 0., 1., 0. ); RiTransformBegin(); RiTranslate( 0.95, 0., 0. ); RiRotate( -90., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformBegin(); RiTranslate( -0.95, 0., 0. ); RiRotate( 180., 0., 0., 1. ); RiCylinder( 0.05, -0.95, 0.95, 90., RI_NULL ); RiTransformEnd(); RiTransformEnd(); break; } case CUSTOM: { //cout <<"custom : "<<options.customRibFile<<endl; if ( fileExists( options.customRibFile.c_str() ) ) { RiReadArchive( const_cast< RtToken >( options.customRibFile.c_str() ), NULL, RI_NULL ); } break; } case SPHERE: default: { RiRotate( 60., 1., 0., 0. ); RiReverseOrientation(); RiSphere( 0.5, -0.5, 0.5, 360., RI_NULL ); break; } } RiAttributeEnd(); /* * Backplane */ if( options.backPlane ) { if ( options.customBackplane.empty() ) { RiAttributeBegin(); RiScale( 0.91, 0.91, 0.91 ); if( MString("displacement")==shader_type_TempForRefactoring/*SHADER_TYPE_DISPLACEMENT == currentShader.shader_type*/ ) // [2/14/2012 yaoyansi] { RtColor bg = { 0.698, 0.698, 0. }; RiColor( bg ); } else RiSurface( const_cast< RtToken >( options.backPlaneShader.c_str() ), RI_NULL ); static RtPoint backplane[4] = { { -1., 1., 2. }, { 1., 1., 2. }, { -1., -1., 2. }, { 1., -1., 2. } }; RiPatch( RI_BILINEAR, RI_P, (RtPointer) backplane, RI_NULL ); RiAttributeEnd(); } else { if ( fileExists( options.customBackplane.c_str() ) ) { RiAttributeBegin(); RiScale( 1., 1., -1. ); RiReadArchive( const_cast< RtString >( options.customBackplane.c_str() ), NULL, RI_NULL ); RiAttributeEnd(); } } } RiWorldEnd(); /* this caused maya to hang up under windoof - Alf #ifdef _WIN32 // Wait until the renderer is done while( !fileFullyAccessible( options.displayName.c_str() ) ); #endif */ RiEnd(); if(liqglo.m_logMsgFlush) { fflush( NULL ); } }
IECore::DataPtr convert( const MCommandResult &result ) { MStatus s; switch (result.resultType()) { case MCommandResult::kInvalid: { // No result return 0; } case MCommandResult::kInt: { int i; s = result.getResult(i); assert(s); IECore::IntDataPtr data = new IECore::IntData(); data->writable() = i; return data; } case MCommandResult::kIntArray: { MIntArray v; s = result.getResult(v); assert(s); unsigned sz = v.length(); IECore::IntVectorDataPtr data = new IECore::IntVectorData(); data->writable().resize(sz); for (unsigned i = 0; i < sz; i++) { (data->writable())[i] = v[i]; } return data; } case MCommandResult::kDouble: { double d; s = result.getResult(d); assert(s); IECore::FloatDataPtr data = new IECore::FloatData(); data->writable() = static_cast<float>(d); return data; } case MCommandResult::kDoubleArray: { MDoubleArray v; s = result.getResult(v); assert(s); unsigned sz = v.length(); IECore::DoubleVectorDataPtr data = new IECore::DoubleVectorData(); data->writable().resize(sz); for (unsigned i = 0; i < sz; i++) { data->writable()[i] = v[i]; } return data; } case MCommandResult::kString: { MString str; s = result.getResult(str); assert(s); IECore::StringDataPtr data = new IECore::StringData(); data->writable() = std::string(str.asChar()); return data; } case MCommandResult::kStringArray: { MStringArray v; s = result.getResult(v); assert(s); unsigned sz = v.length(); IECore::StringVectorDataPtr data = new IECore::StringVectorData(); data->writable().resize(sz); for (unsigned i = 0; i < sz; i++) { data->writable()[i] = std::string(v[i].asChar()); } return data; } case MCommandResult::kVector: { MVector v; s = result.getResult(v); assert(s); IECore::V3fDataPtr data = new IECore::V3fData(); data->writable() = Imath::V3f(v.x, v.y, v.z); return data; } case MCommandResult::kVectorArray: { MVectorArray v; s = result.getResult(v); assert(s); unsigned sz = v.length(); IECore::V3fVectorDataPtr data = new IECore::V3fVectorData(); data->writable().resize(sz); for (unsigned i = 0; i < sz; i++) { data->writable()[i] = Imath::V3f(v[i].x, v[i].y, v[i].z); } return data; } case MCommandResult::kMatrix: { MDoubleArray v; int numRows, numColumns; s = result.getResult(v, numRows, numColumns); assert(s); if (numRows > 4 || numColumns > 4) { throw IECoreMaya::StatusException( MS::kFailure ); } IECore::M44fDataPtr data = new IECore::M44fData(); for (int i = 0; i < numColumns; i++) { for (int j = 0; j < numRows; j++) { (data->writable())[i][j] = v[i*numRows+j]; } } return data; } case MCommandResult::kMatrixArray: { return 0; } default: assert( false ); return 0; } }
void LuxRenderer::defineTriangleMesh(mtlu_MayaObject *obj, bool noObjectDef = false) { MObject meshObject = obj->mobject; MStatus stat = MStatus::kSuccess; MFnMesh meshFn(meshObject, &stat); CHECK_MSTATUS(stat); MItMeshPolygon faceIt(meshObject, &stat); CHECK_MSTATUS(stat); MPointArray points; meshFn.getPoints(points); MFloatVectorArray normals; meshFn.getNormals( normals, MSpace::kWorld ); MFloatArray uArray, vArray; meshFn.getUVs(uArray, vArray); logger.debug(MString("Translating mesh object ") + meshFn.name().asChar()); MString meshFullName = obj->fullNiceName; MIntArray trianglesPerFace, triVertices; meshFn.getTriangles(trianglesPerFace, triVertices); int numTriangles = 0; for( size_t i = 0; i < trianglesPerFace.length(); i++) numTriangles += trianglesPerFace[i]; // lux render does not have a per vertex per face normal definition, here we can use one normal and uv per vertex only // So I create the triangles with unique vertices, normals and uvs. Of course this way vertices etc. cannot be shared. int numPTFloats = numTriangles * 3 * 3; logger.debug(MString("Num Triangles: ") + numTriangles + " num tri floats " + numPTFloats); float *floatPointArray = new float[numPTFloats]; float *floatNormalArray = new float[numPTFloats]; float *floatUvArray = new float[numTriangles * 3 * 2]; logger.debug(MString("Allocated ") + numPTFloats + " floats for point and normals"); MIntArray triangelVtxIdListA; MFloatArray floatPointArrayA; MPointArray triPoints; MIntArray triVtxIds; MIntArray faceVtxIds; MIntArray faceNormalIds; int *triangelVtxIdList = new int[numTriangles * 3]; for( uint sgId = 0; sgId < obj->shadingGroups.length(); sgId++) { MString slotName = MString("slot_") + sgId; } int triCount = 0; int vtxCount = 0; for(faceIt.reset(); !faceIt.isDone(); faceIt.next()) { int faceId = faceIt.index(); int numTris; faceIt.numTriangles(numTris); faceIt.getVertices(faceVtxIds); MIntArray faceUVIndices; faceNormalIds.clear(); for( uint vtxId = 0; vtxId < faceVtxIds.length(); vtxId++) { faceNormalIds.append(faceIt.normalIndex(vtxId)); int uvIndex; faceIt.getUVIndex(vtxId, uvIndex); faceUVIndices.append(uvIndex); } int perFaceShadingGroup = 0; if( obj->perFaceAssignments.length() > 0) perFaceShadingGroup = obj->perFaceAssignments[faceId]; //logger.info(MString("Face ") + faceId + " will receive SG " + perFaceShadingGroup); for( int triId = 0; triId < numTris; triId++) { int faceRelIds[3]; faceIt.getTriangle(triId, triPoints, triVtxIds); for( uint triVtxId = 0; triVtxId < 3; triVtxId++) { for(uint faceVtxId = 0; faceVtxId < faceVtxIds.length(); faceVtxId++) { if( faceVtxIds[faceVtxId] == triVtxIds[triVtxId]) { faceRelIds[triVtxId] = faceVtxId; } } } uint vtxId0 = faceVtxIds[faceRelIds[0]]; uint vtxId1 = faceVtxIds[faceRelIds[1]]; uint vtxId2 = faceVtxIds[faceRelIds[2]]; uint normalId0 = faceNormalIds[faceRelIds[0]]; uint normalId1 = faceNormalIds[faceRelIds[1]]; uint normalId2 = faceNormalIds[faceRelIds[2]]; uint uvId0 = faceUVIndices[faceRelIds[0]]; uint uvId1 = faceUVIndices[faceRelIds[1]]; uint uvId2 = faceUVIndices[faceRelIds[2]]; floatPointArray[vtxCount * 3] = points[vtxId0].x; floatPointArray[vtxCount * 3 + 1] = points[vtxId0].y; floatPointArray[vtxCount * 3 + 2] = points[vtxId0].z; floatNormalArray[vtxCount * 3] = normals[normalId0].x; floatNormalArray[vtxCount * 3 + 1] = normals[normalId0].y; floatNormalArray[vtxCount * 3 + 2] = normals[normalId0].z; floatUvArray[vtxCount * 2] = uArray[uvId0]; floatUvArray[vtxCount * 2 + 1] = vArray[uvId0]; vtxCount++; floatPointArray[vtxCount * 3] = points[vtxId1].x; floatPointArray[vtxCount * 3 + 1] = points[vtxId1].y; floatPointArray[vtxCount * 3 + 2] = points[vtxId1].z; floatNormalArray[vtxCount * 3] = normals[normalId1].x; floatNormalArray[vtxCount * 3 + 1] = normals[normalId1].y; floatNormalArray[vtxCount * 3 + 2] = normals[normalId1].z; floatUvArray[vtxCount * 2] = uArray[uvId1]; floatUvArray[vtxCount * 2 + 1] = vArray[uvId1]; vtxCount++; floatPointArray[vtxCount * 3] = points[vtxId2].x; floatPointArray[vtxCount * 3 + 1] = points[vtxId2].y; floatPointArray[vtxCount * 3 + 2] = points[vtxId2].z; floatNormalArray[vtxCount * 3] = normals[normalId2].x; floatNormalArray[vtxCount * 3 + 1] = normals[normalId2].y; floatNormalArray[vtxCount * 3 + 2] = normals[normalId2].z; floatUvArray[vtxCount * 2] = uArray[uvId2]; floatUvArray[vtxCount * 2 + 1] = vArray[uvId2]; vtxCount++; //logger.debug(MString("Vertex count: ") + vtxCount + " maxId " + ((vtxCount - 1) * 3 + 2) + " ptArrayLen " + (numTriangles * 3 * 3)); triangelVtxIdList[triCount * 3] = triCount * 3; triangelVtxIdList[triCount * 3 + 1] = triCount * 3 + 1; triangelVtxIdList[triCount * 3 + 2] = triCount * 3 + 2; triCount++; } } //generatetangents bool Generate tangent space using miktspace, useful if mesh has a normal map that was also baked using miktspace (such as blender or xnormal) false //subdivscheme string Subdivision algorithm, options are "loop" and "microdisplacement" "loop" //displacementmap string Name of the texture used for the displacement. Subdivscheme parameter must always be provided, as load-time displacement is handled by the loop-subdivision code. none - optional. (loop subdiv can be used without displacement, microdisplacement will not affect the mesh without a displacement map specified) //dmscale float Scale of the displacement (for an LDR map, this is the maximum height of the displacement in meter) 0.1 //dmoffset float Offset of the displacement. 0 //dmnormalsmooth bool Smoothing of the normals of the subdivided faces. Only valid for loop subdivision. true //dmnormalsplit bool Force the mesh to split along breaks in the normal. If a mesh has no normals (flat-shaded) it will rip open on all edges. Only valid for loop subdivision. false //dmsharpboundary bool Try to preserve mesh boundaries during subdivision. Only valid for loop subdivision. false //nsubdivlevels integer Number of subdivision levels. This is only recursive for loop subdivision, microdisplacement will need much larger values (such as 50). 0 bool generatetangents = false; getBool(MString("mtlu_mesh_generatetangents"), meshFn, generatetangents); int subdivscheme = 0; const char *subdAlgos[] = {"loop", "microdisplacement"}; getInt(MString("mtlu_mesh_subAlgo"), meshFn, subdivscheme); const char *subdalgo = subdAlgos[subdivscheme]; float dmscale; getFloat(MString("mtlu_mesh_dmscale"), meshFn, dmscale); float dmoffset; getFloat(MString("mtlu_mesh_dmoffset"), meshFn, dmoffset); MString displacementmap; getString(MString("mtlu_mesh_displacementMap"), meshFn, displacementmap); const char *displacemap = displacementmap.asChar(); bool dmnormalsmooth = true; getBool(MString("mtlu_mesh_dmnormalsmooth"), meshFn, dmnormalsmooth); bool dmnormalsplit = false; getBool(MString("mtlu_mesh_dmnormalsplit"), meshFn, dmnormalsplit); bool dmsharpboundary = false; getBool(MString("mtlu_mesh_dmsharpboundary"), meshFn, dmsharpboundary); int nsubdivlevels = 0; getInt(MString("mtlu_mesh_subdivlevel"), meshFn, nsubdivlevels); // a displacment map needs its own texture defintion MString displacementTextureName = ""; if(displacementmap.length() > 0) { ParamSet dmParams = CreateParamSet(); dmParams->AddString("filename", &displacemap); displacementTextureName = meshFn.name() + "_displacementMap"; this->lux->texture(displacementTextureName.asChar(), "float", "imagemap", boost::get_pointer(dmParams)); } ParamSet triParams = CreateParamSet(); int numPointValues = numTriangles * 3; int numUvValues = numTriangles * 3 * 2; clock_t startTime = clock(); logger.info(MString("Adding mesh values to params.")); triParams->AddInt("indices", triangelVtxIdList, numTriangles * 3); triParams->AddPoint("P", floatPointArray, numPointValues); triParams->AddNormal("N", floatNormalArray, numPointValues); triParams->AddFloat("uv", floatUvArray, numUvValues); if( nsubdivlevels > 0) triParams->AddInt("nsubdivlevels", &nsubdivlevels, 1); triParams->AddBool("generatetangents", &generatetangents, 1); triParams->AddString("subdivscheme", &subdalgo , 1); if(displacementmap.length() > 0) { triParams->AddFloat("dmoffset", &dmoffset, 1); triParams->AddFloat("dmscale", &dmscale, 1); const char *dmft = displacementTextureName.asChar(); triParams->AddString("displacementmap", &dmft); } triParams->AddBool("dmnormalsmooth", &dmnormalsmooth, 1); triParams->AddBool("dmnormalsplit", &dmnormalsplit, 1); triParams->AddBool("dmsharpboundary", &dmsharpboundary, 1); clock_t pTime = clock(); if(!noObjectDef) this->lux->objectBegin(meshFullName.asChar()); this->lux->shape("trianglemesh", boost::get_pointer(triParams)); if(!noObjectDef) this->lux->objectEnd(); clock_t eTime = clock(); logger.info(MString("Timing: Parameters: ") + ((pTime - startTime)/CLOCKS_PER_SEC) + " objTime " + ((eTime - pTime)/CLOCKS_PER_SEC) + " all " + ((eTime - startTime)/CLOCKS_PER_SEC)); return; }
//-***************************************************************************** MStatus AbcExport::doIt( const MArgList & args ) { MStatus status; MTime oldCurTime = MAnimControl::currentTime(); MArgParser argData( syntax(), args, &status ); if ( status != MS::kSuccess ) { return status; } unsigned int numberOfArguments = args.length(); MString msg; msg += "AlembicSimpleAbcExport [options] OutputFileName.abc\n\n"; msg += "Options:\n"; msg += "-h / help Print this message.\n"; msg += "\n"; msg += "-fs / frameStart int (default: 0)\n"; msg += "The export start frame\n"; msg += "\n"; msg += "-fe / frameEnd int (default: 0)\n"; msg += "The export end frame\n"; msg += "\n"; msg += "-v / verbose Verbose output\n"; msg += "\n"; if ( argData.isFlagSet( "help" ) ) { MGlobal::displayInfo( msg ); return MS::kSuccess; } bool verbose = argData.isFlagSet( "verbose" ); int frameStart = 0; if ( argData.isFlagSet( "frameStart" ) ) { argData.getFlagArgument( "frameStart", 0, frameStart ); } int frameEnd = 0; if ( argData.isFlagSet( "frameEnd" ) ) { argData.getFlagArgument( "frameEnd", 0, frameEnd ); } // status = argData.getCommandArgument(0, argStr); // Get filenameArgument MString fileNameStr = args.asString( numberOfArguments-1, &status ); // Okay, do it. Parameters params; params.fileName = fileNameStr.asChar(); params.startFrame = frameStart; params.endFrame = frameEnd; params.verbose = verbose; params.polysAsSubds = false; params.deforming = true; params.allUserAttributes = true; params.allMayaAttributes = false; try { status = AbcExportSelected( params ); } catch ( std::exception &exc ) { MGlobal::displayError( exc.what() ); status = MS::kFailure; } catch ( ... ) { MGlobal::displayError( "AlembicSimpleAbcExport: UNKNOWN EXCEPTION" ); status = MS::kFailure; } return status; }
//-***************************************************************************** MStatus AbcExportSelected( const Parameters &iConfig ) { // Abc::Init(); //-************************************************************************* // CREATE SELECTION LIST //-************************************************************************* MSelectionList slist; MGlobal::getActiveSelectionList( slist ); if ( slist.length() == 0 ) { MGlobal::displayError( "Nothing selected." ); return MS::kFailure; } //-************************************************************************* // CREATE THE ARCHIVE //-************************************************************************* if ( iConfig.fileName == "UNSPECIFIED_FILE_NAME.abc" || iConfig.fileName == "" ) { MGlobal::displayError( "No filename specified." ); return MStatus::kFailure; } // Create the time sampling. Abc::TimeSamplingType tSmpType; if ( iConfig.endFrame > iConfig.startFrame ) { tSmpType = Abc::TimeSamplingType( // Increment, in seconds, between samples. ( Abc::chrono_t ) MTime( 1.0, MTime::uiUnit() ).as( MTime::kSeconds ) ); } // Get FPS Abc::chrono_t fps = MTime( 1.0, MTime::kSeconds ).as( MTime::uiUnit() ); Top top( iConfig.fileName, tSmpType, fps ); std::cout << "AlembicSimpleAbcExport: Opened Alembic Archive: " << top.getName() << " for writing." << std::endl; // Build comments std::string comments = "AlembicSimpleAbcExport v0.1.1"; comments += "\n"; MString exportedFromStr = "(Exported from " + MFileIO::currentFile() + ")"; comments += exportedFromStr.asChar(); comments += "\n"; // top.setComments( comments ); //-********************************************************************* // BUILD TREE OF NODE:OBJECT PAIRS TO EXPORT //-********************************************************************* // Create the factory Factory factory( iConfig ); for ( MItSelectionList liter( slist ); !liter.isDone(); liter.next() ) { MDagPath dagPath; MObject component; liter.getDagPath( dagPath, component ); // This will skip nodes we've already visited. HAVE NO // FEAR. factory.makeTree( top, dagPath, 1000000, tSmpType ); } std::cout << "AlembicSimpleAbcExport: Created DAG Tree to export." << std::endl; //-********************************************************************* // EXPORT SAMPLES PER FRAME //-********************************************************************* // Loop over time MComputation computation; computation.beginComputation(); for ( int frame = iConfig.startFrame; frame <= iConfig.endFrame; ++frame ) { // Get a time. MTime thisTime( ( double )frame, MTime::uiUnit() ); // Set the time. MAnimControl::setCurrentTime( thisTime ); // Get the chrono and the index Abc::index_t frameIndex = ( Abc::index_t )( frame - iConfig.startFrame ); Abc::chrono_t frameTime = ( Abc::chrono_t )thisTime.as( MTime::kSeconds ); // Is this necessary to force an eval? Sometimes? // MGlobal::viewFrame( t ); // M3dView currentView = M3dView::active3dView(); // currentView.refresh( true, true, true ); // Write the frame. top.writeSample( Abc::OSampleSelector( frameIndex, frameTime ) ); std::cout << "AlembicSimpleAbcExport: Wrote frame: " << frame << std::endl; if ( computation.isInterruptRequested() ) { break; } } top.close(); computation.endComputation(); // H5close(); std::cout << "AlembicSimpleAbcExport: Closed Archive." << std::endl; return MS::kSuccess; }
void FujiRenderer::render() { const int W = this->mtfu_renderGlobals->imgWidth; const int H = this->mtfu_renderGlobals->imgHeight; ID object; ID shader; logger.info("------- Starting fujiyama rendering --------"); // Display pre render infos try{ ID framebuffer; ID light; SiOpenScene(); renderer = SiNewRenderer(); if (renderer == SI_BADID) { fprintf(stderr, "Could not allocate renderer\n"); throw("Could not allocate renderer"); } /* Plugin */ if (SiOpenPlugin("PlasticShader")) { } this->defineCamera(); this->defineLights(); this->defineSettings(); shader = SiNewShader("PlasticShader"); if (shader == SI_BADID) { fprintf(stderr, "Could not create shader: PlasticShader\n"); throw("Could not create shader: PlasticShader"); } for( uint objId = 0; objId < this->mtfu_scene->objectList.size(); objId++) { mtfu_MayaObject *obj = (mtfu_MayaObject *)this->mtfu_scene->objectList[objId]; ID mesh = SI_BADID; if( obj->exportFileNames.size() > 0) { mesh = SiNewMesh(obj->exportFileNames[0].asChar()); if (mesh == SI_BADID) { logger.error(MString("Could not create mesh from file: ") + obj->exportFileNames[0]); continue; } if( mesh == SI_BADID) continue; obj->objectID = mesh; }else{ if( obj->origObject != NULL ) { mtfu_MayaObject *origObj = (mtfu_MayaObject *)obj->origObject; mesh = origObj->objectID; if( mesh == SI_BADID) continue; }else{ continue; } }; object = SiNewObjectInstance(mesh); if (object == SI_BADID) { throw("Could not create object instance"); } MTransformationMatrix objTMatrix(obj->dagPath.inclusiveMatrix()); double rot[3]; double scale[3]; MTransformationMatrix::RotationOrder rotOrder = MTransformationMatrix::kXYZ; objTMatrix.getRotation(rot, rotOrder, MSpace::kWorld); MVector pos = objTMatrix.getTranslation(MSpace::kWorld); objTMatrix.getScale(scale, MSpace::kWorld); SiSetProperty3(object, "translate", pos[0], pos[1], pos[2]); SiSetProperty3(object, "rotate", RadToDeg(rot[0]), RadToDeg(rot[1]), RadToDeg(rot[2])); SiSetProperty3(object, "scale", scale[0], scale[1], scale[2]); logger.debug(MString("SetProperty3 ") + obj->shortName + " translate " + pos[0] + " " + pos[1] + " " + pos[2]); logger.debug(MString("SetProperty3 ") + obj->shortName + " rotate " + RadToDeg(rot[0]) + " " + RadToDeg(rot[1]) + " " + RadToDeg(rot[2])); SiAssignShader(object, shader); } framebuffer = SiNewFrameBuffer("rgba"); if (framebuffer == SI_BADID) { fprintf(stderr, "Could not allocate framebuffer\n"); throw("Could not allocate framebuffer"); } SiAssignFrameBuffer(renderer, framebuffer); callbacks.setCallbacks(renderer); MString imageOutputFile = this->mtfu_renderGlobals->imageOutputFile; FujiImgTools::ImgTools imgTools; MString fbFile = imageOutputFile + ".fb"; Status result = SiRenderScene(renderer); if( result == SI_BADID ) { logger.error("Renderer exited with error."); SiCloseScene(); throw("Renderer exited with error."); } SiSaveFrameBuffer(framebuffer, fbFile.asChar()); imgTools.FrameBufferToExr(fbFile); SiCloseScene(); }catch(char *errorMsg){ logger.error(errorMsg); EventQueue::Event e; e.data = NULL; e.type = EventQueue::Event::RENDERERROR; theRenderEventQueue()->push(e); } EventQueue::Event e; e.data = NULL; e.type = EventQueue::Event::FRAMEDONE; theRenderEventQueue()->push(e); }
PXR_NAMESPACE_OPEN_SCOPE /* static */ bool PxrUsdMayaTranslatorMesh::Create( const UsdGeomMesh& mesh, MObject parentNode, const PxrUsdMayaPrimReaderArgs& args, PxrUsdMayaPrimReaderContext* context) { if (!mesh) { return false; } const UsdPrim& prim = mesh.GetPrim(); MStatus status; // Create node (transform) MObject mayaNodeTransformObj; if (!PxrUsdMayaTranslatorUtil::CreateTransformNode(prim, parentNode, args, context, &status, &mayaNodeTransformObj)) { return false; } VtArray<GfVec3f> points; VtArray<GfVec3f> normals; VtArray<int> faceVertexCounts; VtArray<int> faceVertexIndices; UsdAttribute fvc = mesh.GetFaceVertexCountsAttr(); if (fvc.ValueMightBeTimeVarying()){ // at some point, it would be great, instead of failing, to create a usd/hydra proxy node // for the mesh, perhaps? For now, better to give a more specific error MGlobal::displayError( TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexCounts). Skipping...", prim.GetPath().GetText()).c_str()); return false; } else { // for any non-topo-varying mesh, sampling at zero will get us the right answer fvc.Get(&faceVertexCounts, 0); } UsdAttribute fvi = mesh.GetFaceVertexIndicesAttr(); if (fvi.ValueMightBeTimeVarying()){ // at some point, it would be great, instead of failing, to create a usd/hydra proxy node // for the mesh, perhaps? For now, better to give a more specific error MGlobal::displayError( TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexIndices). Skipping...", prim.GetPath().GetText()).c_str()); return false; } else { // for any non-topo-varying mesh, sampling at zero will get us the right answer fvi.Get(&faceVertexIndices, 0); } // Sanity Checks. If the vertex arrays are empty, skip this mesh if (faceVertexCounts.size() == 0 || faceVertexIndices.size() == 0) { MGlobal::displayError( TfStringPrintf("FaceVertex arrays are empty [Count:%zu Indices:%zu] on Mesh <%s>. Skipping...", faceVertexCounts.size(), faceVertexIndices.size(), prim.GetPath().GetText()).c_str()); return false; // invalid mesh, so exit } // Gather points and normals // If args.GetReadAnimData() is TRUE, // pick the first avaiable sample or default UsdTimeCode pointsTimeSample=UsdTimeCode::EarliestTime(); UsdTimeCode normalsTimeSample=UsdTimeCode::EarliestTime(); std::vector<double> pointsTimeSamples; size_t pointsNumTimeSamples = 0; if (args.GetReadAnimData()) { PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetPointsAttr(), args, &pointsTimeSamples); pointsNumTimeSamples = pointsTimeSamples.size(); if (pointsNumTimeSamples>0) { pointsTimeSample = pointsTimeSamples[0]; } std::vector<double> normalsTimeSamples; PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetNormalsAttr(), args, &normalsTimeSamples); if (normalsTimeSamples.size()) { normalsTimeSample = normalsTimeSamples[0]; } } mesh.GetPointsAttr().Get(&points, pointsTimeSample); mesh.GetNormalsAttr().Get(&normals, normalsTimeSample); if (points.size() == 0) { MGlobal::displayError( TfStringPrintf("Points arrays is empty on Mesh <%s>. Skipping...", prim.GetPath().GetText()).c_str()); return false; // invalid mesh, so exit } // == Convert data size_t mayaNumVertices = points.size(); MPointArray mayaPoints(mayaNumVertices); for (size_t i=0; i < mayaNumVertices; i++) { mayaPoints.set( i, points[i][0], points[i][1], points[i][2] ); } MIntArray polygonCounts( faceVertexCounts.cdata(), faceVertexCounts.size() ); MIntArray polygonConnects( faceVertexIndices.cdata(), faceVertexIndices.size() ); // == Create Mesh Shape Node MFnMesh meshFn; MObject meshObj = meshFn.create(mayaPoints.length(), polygonCounts.length(), mayaPoints, polygonCounts, polygonConnects, mayaNodeTransformObj, &status ); if (status != MS::kSuccess) { return false; } // Since we are "decollapsing", we will create a xform and a shape node for each USD prim std::string usdPrimName(prim.GetName().GetText()); std::string shapeName(usdPrimName); shapeName += "Shape"; // Set mesh name and register meshFn.setName(MString(shapeName.c_str()), false, &status); if (context) { std::string usdPrimPath(prim.GetPath().GetText()); std::string shapePath(usdPrimPath); shapePath += "/"; shapePath += shapeName; context->RegisterNewMayaNode( shapePath, meshObj ); // used for undo/redo } // If a material is bound, create (or reuse if already present) and assign it // If no binding is present, assign the mesh to the default shader const TfToken& shadingMode = args.GetShadingMode(); PxrUsdMayaTranslatorMaterial::AssignMaterial(shadingMode, mesh, meshObj, context); // Mesh is a shape, so read Gprim properties PxrUsdMayaTranslatorGprim::Read(mesh, meshObj, context); // Set normals if supplied MIntArray normalsFaceIds; if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) { for (size_t i=0; i < polygonCounts.length(); i++) { for (int j=0; j < polygonCounts[i]; j++) { normalsFaceIds.append(i); } } if (normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) { MVectorArray mayaNormals(normals.size()); for (size_t i=0; i < normals.size(); i++) { mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i); } if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) { } } } // Determine if PolyMesh or SubdivMesh TfToken subdScheme = PxrUsdMayaMeshUtil::setSubdivScheme(mesh, meshFn, args.GetDefaultMeshScheme()); // If we are dealing with polys, check if there are normals // If we are dealing with SubdivMesh, read additional attributes and SubdivMesh properties if (subdScheme == UsdGeomTokens->none) { if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) { PxrUsdMayaMeshUtil::setEmitNormals(mesh, meshFn, UsdGeomTokens->none); } } else { PxrUsdMayaMeshUtil::setSubdivInterpBoundary(mesh, meshFn, UsdGeomTokens->edgeAndCorner); PxrUsdMayaMeshUtil::setSubdivFVLinearInterpolation(mesh, meshFn); _AssignSubDivTagsToMesh(mesh, meshObj, meshFn); } // Set Holes VtArray<int> holeIndices; mesh.GetHoleIndicesAttr().Get(&holeIndices); // not animatable if ( holeIndices.size() != 0 ) { MUintArray mayaHoleIndices; mayaHoleIndices.setLength( holeIndices.size() ); for (size_t i=0; i < holeIndices.size(); i++) { mayaHoleIndices[i] = holeIndices[i]; } if (meshFn.setInvisibleFaces(mayaHoleIndices) == MS::kFailure) { MGlobal::displayError(TfStringPrintf("Unable to set Invisible Faces on <%s>", meshFn.fullPathName().asChar()).c_str()); } } // GETTING PRIMVARS std::vector<UsdGeomPrimvar> primvars = mesh.GetPrimvars(); TF_FOR_ALL(iter, primvars) { const UsdGeomPrimvar& primvar = *iter; const TfToken& name = primvar.GetBaseName(); const SdfValueTypeName& typeName = primvar.GetTypeName(); // If the primvar is called either displayColor or displayOpacity check // if it was really authored from the user. It may not have been // authored by the user, for example if it was generated by shader // values and not an authored colorset/entity. // If it was not really authored, we skip the primvar. if (name == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName || name == PxrUsdMayaMeshColorSetTokens->DisplayOpacityColorSetName) { if (!PxrUsdMayaRoundTripUtil::IsAttributeUserAuthored(primvar)) { continue; } } // XXX: Maya stores UVs in MFloatArrays and color set data in MColors // which store floats, so we currently only import primvars holding // float-typed arrays. Should we still consider other precisions // (double, half, ...) and/or numeric types (int)? if (typeName == SdfValueTypeNames->Float2Array) { // We assume that Float2Array primvars are UV sets. if (!_AssignUVSetPrimvarToMesh(primvar, meshFn)) { MGlobal::displayWarning( TfStringPrintf("Unable to retrieve and assign data for UV set <%s> on mesh <%s>", name.GetText(), mesh.GetPrim().GetPath().GetText()).c_str()); } } else if (typeName == SdfValueTypeNames->FloatArray || typeName == SdfValueTypeNames->Float3Array || typeName == SdfValueTypeNames->Color3fArray || typeName == SdfValueTypeNames->Float4Array || typeName == SdfValueTypeNames->Color4fArray) { if (!_AssignColorSetPrimvarToMesh(mesh, primvar, meshFn)) { MGlobal::displayWarning( TfStringPrintf("Unable to retrieve and assign data for color set <%s> on mesh <%s>", name.GetText(), mesh.GetPrim().GetPath().GetText()).c_str()); } } } // We only vizualize the colorset by default if it is "displayColor". MStringArray colorSetNames; if (meshFn.getColorSetNames(colorSetNames)==MS::kSuccess) { for (unsigned int i=0; i < colorSetNames.length(); i++) { const MString colorSetName = colorSetNames[i]; if (std::string(colorSetName.asChar()) == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName.GetString()) { MFnMesh::MColorRepresentation csRep= meshFn.getColorRepresentation(colorSetName); if (csRep==MFnMesh::kRGB || csRep==MFnMesh::kRGBA) { // both of these are needed to show the colorset. MPlug plg=meshFn.findPlug("displayColors"); if ( !plg.isNull() ) { plg.setBool(true); } meshFn.setCurrentColorSetName(colorSetName); } break; } } } // == Animate points == // Use blendShapeDeformer so that all the points for a frame are contained in a single node // if (pointsNumTimeSamples > 0) { MPointArray mayaPoints(mayaNumVertices); MObject meshAnimObj; MFnBlendShapeDeformer blendFn; MObject blendObj = blendFn.create(meshObj); if (context) { context->RegisterNewMayaNode( blendFn.name().asChar(), blendObj ); // used for undo/redo } for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) { mesh.GetPointsAttr().Get(&points, pointsTimeSamples[ti]); for (unsigned int i=0; i < mayaNumVertices; i++) { mayaPoints.set( i, points[i][0], points[i][1], points[i][2] ); } // == Create Mesh Shape Node MFnMesh meshFn; if ( meshAnimObj.isNull() ) { meshAnimObj = meshFn.create(mayaPoints.length(), polygonCounts.length(), mayaPoints, polygonCounts, polygonConnects, mayaNodeTransformObj, &status ); if (status != MS::kSuccess) { continue; } } else { // Reuse the already created mesh by copying it and then setting the points meshAnimObj = meshFn.copy(meshAnimObj, mayaNodeTransformObj, &status); meshFn.setPoints(mayaPoints); } // Set normals if supplied // // NOTE: This normal information is not propagated through the blendShapes, only the controlPoints. // mesh.GetNormalsAttr().Get(&normals, pointsTimeSamples[ti]); if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices()) && normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) { MVectorArray mayaNormals(normals.size()); for (size_t i=0; i < normals.size(); i++) { mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i); } if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) { } } // Add as target and set as an intermediate object blendFn.addTarget(meshObj, ti, meshAnimObj, 1.0); meshFn.setIntermediateObject(true); if (context) { context->RegisterNewMayaNode( meshFn.fullPathName().asChar(), meshAnimObj ); // used for undo/redo } } // Animate the weights so that mesh0 has a weight of 1 at frame 0, etc. MFnAnimCurve animFn; // Construct the time array to be used for all the keys MTimeArray timeArray; timeArray.setLength(pointsNumTimeSamples); for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) { timeArray.set( MTime(pointsTimeSamples[ti]), ti); } // Key/Animate the weights MPlug plgAry = blendFn.findPlug( "weight" ); if ( !plgAry.isNull() && plgAry.isArray() ) { for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) { MPlug plg = plgAry.elementByLogicalIndex(ti, &status); MDoubleArray valueArray(pointsNumTimeSamples, 0.0); valueArray[ti] = 1.0; // Set the time value where this mesh's weight should be 1.0 MObject animObj = animFn.create(plg, NULL, &status); animFn.addKeys(&timeArray, &valueArray); if (context) { context->RegisterNewMayaNode(animFn.name().asChar(), animObj ); // used for undo/redo } } } } return true; }
MStatus viewCapture::doIt( const MArgList& args ) { MStatus status = MS::kSuccess; if ( args.length() != 1 ) { // Need the file name argument // return MS::kFailure; } MString fileName; args.get( 0, fileName ); // Get the active 3D view // M3dView view = M3dView::active3dView(); // Capture the current view // view.refresh(); view.beginGL(); // Set the target for our pixel read to be the front buffer. First, the // current state is saved using the glPushAttrib call. It is important // to leave the OpenGL in the same state that we found it. // glPushAttrib( GL_PIXEL_MODE_BIT ); int width = view.portWidth(); int height = view.portHeight(); // Allocate buffers for the pixel data // GLfloat * red = new GLfloat[width*height]; GLfloat * green = new GLfloat[width*height]; GLfloat * blue = new GLfloat[width*height]; // Read the values from the OpenGL frame buffer // glReadBuffer( GL_FRONT ); glReadPixels( 0, 0, width, height, GL_RED, GL_FLOAT, red ); glReadPixels( 0, 0, width, height, GL_GREEN, GL_FLOAT, green ); glReadPixels( 0, 0, width, height, GL_BLUE, GL_FLOAT, blue ); // Put the gl read target back // glPopAttrib(); view.endGL(); // Write file as a PPM // Pic_Pixel * line = PixelAlloc( width ); int idx; Pic * file = PicOpen( fileName.asChar(), (short) width, (short) height ); if ( NULL != file ) { for ( int row = height - 1; row >= 0; row-- ) { // Covert the row of pixels into PPM format // for ( int col = 0; col < width; col++ ) { // Find the array elements for this pixel // idx = ( row * width ) + ( col ); line[col].r = (Pic_byte)( red[idx] * 255.0 ); line[col].g = (Pic_byte)( green[idx] * 255.0 ); line[col].b = (Pic_byte)( blue[idx] * 255.0 ); } // Write the line // if ( !PicWriteLine( file, line ) ) { status = MS::kFailure; return MS::kFailure; } } PicClose( file ); } delete []red; delete []green; delete []blue; PixelFree( line ); return status; }
MStatus HesMeshNode::compute( const MPlug& plug, MDataBlock& data ) { MStatus stat; MPlug pnames(thisMObject(), ameshname); const unsigned numMeshes = pnames.numElements(); MString cacheName = data.inputValue( input ).asString(); std::string substitutedCacheName(cacheName.asChar()); EnvVar::replace(substitutedCacheName); MArrayDataHandle meshNameArray = data.inputArrayValue( ameshname ); MArrayDataHandle meshArry = data.outputArrayValue(outMesh, &stat); bool hesStat = false; if( plug.array() == outMesh ) { const unsigned idx = plug.logicalIndex(); if(BaseUtil::IsImporting) hesStat = true; else { if(idx == 0) AHelper::Info<std::string>(" hes mesh open file ", substitutedCacheName ); hesStat = BaseUtil::OpenHes(substitutedCacheName, HDocument::oReadOnly); } if(!hesStat) { AHelper::Info<std::string >("hes mesh cannot open file ", substitutedCacheName); return MS::kFailure; } meshNameArray.jumpToElement(idx); const MString meshName = meshNameArray.inputValue().asString(); if(!BaseUtil::HesDoc->find(meshName.asChar())) { AHelper::Info<MString>(" hes cannot find mesh ", meshName ); return MS::kFailure; } meshArry.jumpToElement(idx); MDataHandle hmesh = meshArry.outputValue(); HPolygonalMesh entryMesh(meshName.asChar() ); APolygonalMesh dataMesh; entryMesh.load(&dataMesh); entryMesh.close(); MFnMeshData dataCreator; MObject outMeshData = dataCreator.create(&stat); if( !stat ) { MGlobal::displayWarning("hes mesh cannot create " + meshName); return MS::kFailure; } AHelper::Info<MString>(" hes init mesh ", meshName); HesperisPolygonalMeshCreator::create(&dataMesh, outMeshData); hmesh.set(outMeshData); data.setClean(plug); if( (idx+1)>=numMeshes ) { if(!BaseUtil::IsImporting) { AHelper::Info<std::string>(" hes mesh close file ", substitutedCacheName ); BaseUtil::CloseHes(); } } } else { return MS::kUnknownParameter; } return MS::kSuccess; }
TfToken usdWriteJob::writeVariants(const UsdPrim &usdRootPrim) { // Init parameters for filtering and setting the active variant std::string defaultModelingVariant; // Get the usdVariantRootPrimPath (optionally filter by renderLayer prefix) MayaPrimWriterPtr firstPrimWriterPtr = *mMayaPrimWriterList.begin(); std::string firstPrimWriterPathStr( firstPrimWriterPtr->getDagPath().fullPathName().asChar() ); std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), '|', '/'); std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), ':', '_'); // replace namespace ":" with "_" SdfPath usdVariantRootPrimPath(firstPrimWriterPathStr); usdVariantRootPrimPath = usdVariantRootPrimPath.GetPrefixes()[0]; // Create a new usdVariantRootPrim and reference the Base Model UsdRootPrim // This is done for reasons as described above under mArgs.usdModelRootOverridePath UsdPrim usdVariantRootPrim = mStage->DefinePrim(usdVariantRootPrimPath); TfToken defaultPrim = usdVariantRootPrim.GetName(); usdVariantRootPrim.GetReferences().AppendInternalReference(usdRootPrim.GetPath()); usdVariantRootPrim.SetActive(true); usdRootPrim.SetActive(false); // Loop over all the renderLayers for (unsigned int ir=0; ir < mRenderLayerObjs.length(); ++ir) { SdfPathTable<bool> tableOfActivePaths; MFnRenderLayer renderLayerFn( mRenderLayerObjs[ir] ); MString renderLayerName = renderLayerFn.name(); std::string variantName(renderLayerName.asChar()); // Determine default variant. Currently unsupported //MPlug renderLayerDisplayOrderPlug = renderLayerFn.findPlug("displayOrder", true); //int renderLayerDisplayOrder = renderLayerDisplayOrderPlug.asShort(); // The Maya default RenderLayer is also the default modeling variant if (mRenderLayerObjs[ir] == MFnRenderLayer::defaultRenderLayer()) { defaultModelingVariant=variantName; } // Make the renderlayer being looped the current one MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+ renderLayerName, false, false); // == ModelingVariants == // Identify prims to activate // Put prims and parent prims in a SdfPathTable // Then use that membership to determine if a prim should be Active. // It has to be done this way since SetActive(false) disables access to all child prims. MObjectArray renderLayerMemberObjs; renderLayerFn.listMembers(renderLayerMemberObjs); std::vector< SdfPath > activePaths; for (unsigned int im=0; im < renderLayerMemberObjs.length(); ++im) { MFnDagNode dagFn(renderLayerMemberObjs[im]); MDagPath dagPath; dagFn.getPath(dagPath); dagPath.extendToShape(); SdfPath usdPrimPath; if (!TfMapLookup(mDagPathToUsdPathMap, dagPath, &usdPrimPath)) { continue; } usdPrimPath = usdPrimPath.ReplacePrefix(usdPrimPath.GetPrefixes()[0], usdVariantRootPrimPath); // Convert base to variant usdPrimPath tableOfActivePaths[usdPrimPath] = true; activePaths.push_back(usdPrimPath); //UsdPrim usdPrim = mStage->GetPrimAtPath(usdPrimPath); //usdPrim.SetActive(true); } if (!tableOfActivePaths.empty()) { { // == BEG: Scope for Variant EditContext // Create the variantSet and variant UsdVariantSet modelingVariantSet = usdVariantRootPrim.GetVariantSets().AppendVariantSet("modelingVariant"); modelingVariantSet.AppendVariant(variantName); modelingVariantSet.SetVariantSelection(variantName); // Set the Edit Context UsdEditTarget editTarget = modelingVariantSet.GetVariantEditTarget(); UsdEditContext editContext(mStage, editTarget); // == Activate/Deactivate UsdPrims UsdPrimRange it = UsdPrimRange::AllPrims(mStage->GetPseudoRoot()); std::vector<UsdPrim> primsToDeactivate; for ( ; it; ++it) { UsdPrim usdPrim = *it; // For all xformable usdPrims... if (usdPrim && usdPrim.IsA<UsdGeomXformable>()) { bool isActive=false; for (size_t j=0;j<activePaths.size();j++) { //primPathD.HasPrefix(primPathA); SdfPath activePath=activePaths[j]; if (usdPrim.GetPath().HasPrefix(activePath) || activePath.HasPrefix(usdPrim.GetPath())) { isActive=true; break; } } if (isActive==false) { primsToDeactivate.push_back(usdPrim); it.PruneChildren(); } } } // Now deactivate the prims (done outside of the UsdPrimRange // so not to modify the iterator while in the loop) for ( UsdPrim const& prim : primsToDeactivate ) { prim.SetActive(false); } } // == END: Scope for Variant EditContext } } // END: RenderLayer iterations // Set the default modeling variant UsdVariantSet modelingVariantSet = usdVariantRootPrim.GetVariantSet("modelingVariant"); if (modelingVariantSet.IsValid()) { modelingVariantSet.SetVariantSelection(defaultModelingVariant); } return defaultPrim; }
std::string convert( const MString &from ) { return from.asChar(); }
bool DX11ResourceManager::initializeDefaultSurfaceEffect( const MString& effectsLocation, ID3D11Device* D3D, const MString& effectName, const MString& vsName, const MString& psName, const D3D11_INPUT_ELEMENT_DESC* layout, int numLayoutElements ) // // Description: // Initialize default surface effects found in a given directory. // { HRESULT hres; MString effectLocation = effectsLocation + "\\" + effectName + ".hlsl"; ID3DBlob* pVSBlob = NULL; hres = CompileShaderFromFile( effectLocation.asChar(), vsName.asChar(), "vs_4_0", &pVSBlob ); if (FAILED(hres)) { MGlobal::displayInfo("Failed to compile vertex shader " + vsName + " in file: " + effectLocation); return false; } ID3D11VertexShader* pVertexShader = NULL; hres = D3D->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &pVertexShader ); if (FAILED(hres)) { MGlobal::displayInfo("Failed to create vertex shader " + vsName + " in file: " + effectLocation); pVSBlob->Release(); return false; } ID3D11InputLayout* pVertexLayout = NULL; hres = D3D->CreateInputLayout( layout, numLayoutElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &pVertexLayout ); pVSBlob->Release(); if (FAILED(hres)) { MGlobal::displayInfo("Failed to create input layout for file: " + effectLocation); return false; } ID3DBlob* pPSBlob = NULL; hres = CompileShaderFromFile( effectLocation.asChar(), psName.asChar(), "ps_4_0", &pPSBlob ); if (FAILED(hres)) { MGlobal::displayInfo("Failed to compile pixel shader " + psName + " in file: " + effectLocation); pVertexShader->Release(); pVertexLayout->Release(); return false; } ID3D11PixelShader* pPixelShader = NULL; hres = D3D->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &pPixelShader ); pPSBlob->Release(); if (FAILED(hres)) { MGlobal::displayInfo("Failed to create pixel shader " + psName + " in file: " + effectLocation); pVertexShader->Release(); pVertexLayout->Release(); return false; } // Create a new effect item // MGlobal::displayInfo("Maya default pixel shader loaded: " + effectLocation); SurfaceEffectItem *pei = new SurfaceEffectItem; if (pei) { pei->fVertexShader = pVertexShader; pei->fPixelShader = pPixelShader; pei->fInputLayout = pVertexLayout; m_SurfaceEffectItemList[ effectName.asChar() ] = pei; } return true; }