//------------------------------------------------------------------------------ // MString LocatorRepresentation::Factory::creationName( MPxAssembly* /* assembly */, const MString& input ) const { return MString("Locator"); }
MObject createSubD(double iFrame, SubDAndFriends & iNode, MObject & iParent) { Alembic::AbcGeom::ISubDSchema schema = iNode.mMesh.getSchema(); Alembic::AbcCoreAbstract::index_t index, ceilIndex; getWeightAndIndex(iFrame, schema.getTimeSampling(), schema.getNumSamples(), index, ceilIndex); Alembic::AbcGeom::ISubDSchema::Sample samp; schema.get(samp, Alembic::Abc::ISampleSelector(index)); MString name(iNode.mMesh.getName().c_str()); MFnMesh fnMesh; MFloatPointArray pointArray; Alembic::Abc::P3fArraySamplePtr emptyPtr; fillPoints(pointArray, samp.getPositions(), emptyPtr, 0.0); fillTopology(fnMesh, iParent, pointArray, samp.getFaceIndices(), samp.getFaceCounts()); fnMesh.setName(iNode.mMesh.getName().c_str()); setInitialShadingGroup(fnMesh.partialPathName()); MObject obj = fnMesh.object(); setColorsAndUVs(iFrame, fnMesh, schema.getUVsParam(), iNode.mV2s, iNode.mC3s, iNode.mC4s, true); // add the mFn-specific attributes to fnMesh node MFnNumericAttribute numAttr; MString attrName("SubDivisionMesh"); MObject attrObj = numAttr.create(attrName, attrName, MFnNumericData::kBoolean, 1); numAttr.setKeyable(true); numAttr.setHidden(false); fnMesh.addAttribute(attrObj); if (samp.getInterpolateBoundary() > 0) { attrName = MString("interpolateBoundary"); attrObj = numAttr.create(attrName, attrName, MFnNumericData::kBoolean, samp.getInterpolateBoundary()); numAttr.setKeyable(true); numAttr.setHidden(false); fnMesh.addAttribute(attrObj); } if (samp.getFaceVaryingInterpolateBoundary() > 0) { attrName = MString("faceVaryingInterpolateBoundary"); attrObj = numAttr.create(attrName, attrName, MFnNumericData::kBoolean, samp.getFaceVaryingInterpolateBoundary()); numAttr.setKeyable(true); numAttr.setHidden(false); fnMesh.addAttribute(attrObj); } if (samp.getFaceVaryingPropagateCorners() > 0) { attrName = MString("faceVaryingPropagateCorners"); attrObj = numAttr.create(attrName, attrName, MFnNumericData::kBoolean, samp.getFaceVaryingPropagateCorners()); numAttr.setKeyable(true); numAttr.setHidden(false); fnMesh.addAttribute(attrObj); } fillCreasesCornersAndHoles(fnMesh, iNode, samp); return obj; }
MStatus meshInfo5::doIt( const MArgList& args ) { MStatus stat = MS::kSuccess; MSelectionList selection; MGlobal::getActiveSelectionList( selection ); MDagPath dagPath; MObject component; unsigned int i, nVerts; int fIndex, vIndex, fvIndex; MVector fNormal, vNormal, fvNormal; MString txt; MItSelectionList iter( selection ); for ( ; !iter.isDone(); iter.next() ) { iter.getDagPath( dagPath, component ); MFnMesh meshFn( dagPath ); // This handles whole mesh selections and mesh-face component selections MItMeshPolygon faceIter( dagPath, component, &stat ); if( stat == MS::kSuccess ) { txt += MString( "Object: " ) + dagPath.fullPathName() + "\n"; for( ; !faceIter.isDone(); faceIter.next() ) { nVerts = faceIter.polygonVertexCount(); for( i=0; i < nVerts; i++ ) { fvIndex = i; fIndex = faceIter.index(); vIndex = faceIter.vertexIndex( i ); faceIter.getNormal( fNormal ); meshFn.getVertexNormal( vIndex, vNormal ); faceIter.getNormal( fvIndex, fvNormal ); addData( txt, fIndex, vIndex, fvIndex, fNormal, vNormal, fvNormal ); } } } else { // This handles mesh-vertex component selections MItMeshVertex vertIter( dagPath, component, &stat ); if( stat == MS::kSuccess ) { txt += MString( "Object: " ) + dagPath.fullPathName() + "\n"; MIntArray faceIds; MIntArray vertIds; for( ; !vertIter.isDone(); vertIter.next() ) { vIndex = vertIter.index(); vertIter.getNormal( vNormal ); vertIter.getConnectedFaces( faceIds ); for( i=0; i < faceIds.length(); i++ ) { fIndex = faceIds[i]; meshFn.getPolygonNormal( fIndex, fNormal ); meshFn.getFaceVertexNormal( fIndex, vIndex, fvNormal ); meshFn.getPolygonVertices( fIndex, vertIds ); for( fvIndex=0; fvIndex < int(vertIds.length()); fvIndex++ ) { if( vertIds[fvIndex] == vIndex ) break; } addData( txt, fIndex, vIndex, fvIndex, fNormal, vNormal, fvNormal ); } } } } } MGlobal::displayInfo( txt ); return MS::kSuccess; }
// initialize // ------------ //! Initialises the Attributes on the node, and set the evaluation dependencies MStatus NBuddySurfaceToBodyNode::initialize() { MStatus status; //Function sets needed MFnStringData stringData; MFnPluginData dataFn; MFnMatrixData matrixFn; MFnGenericAttribute genFn; MFnTypedAttribute typedAttr; MFnNumericAttribute numAttr; MFnMatrixAttribute mAttr; //Attribute that specifies if the object should be converted to worldspace or localspace _useTransform = numAttr.create( "useTransform", "ut", MFnNumericData::kBoolean, true, &status ); NM_CheckMStatus(status, "ERROR creating useWorldSpace attribute.\n"); status = addAttribute( _useTransform ); //The input transform for the object _inTransform = mAttr.create("inTransform","it", MFnMatrixAttribute::kDouble, &status); mAttr.setStorable( true ); mAttr.setConnectable(true); NM_CheckMStatus(status, "ERROR creating inTransform attribute.\n"); status = addAttribute( _inTransform ); NM_CheckMStatus(status, "ERROR adding inTransform attribute.\n"); //Create the inSurface plug _inSurface = genFn.create( "inSurface", "surf", &status); NM_CheckMStatus( status, "Failed to create inSurface GenericAttribute"); genFn.addAccept(MFnData::kNurbsSurface); genFn.addAccept(MFnData::kMesh); genFn.addAccept(MFnData::kSubdSurface); genFn.setStorable(false); genFn.setCached(false); status = addAttribute( _inSurface ); NM_CheckMStatus(status, "ERROR adding inSurface attribute.\n"); // Create the attribute for the body output _outBody = typedAttr.create("outBody","ob" , naiadBodyData::id , MObject::kNullObj , &status); NM_CheckMStatus(status, "ERROR creating outBody attribute.\n"); typedAttr.setKeyable( false ); typedAttr.setWritable( false ); typedAttr.setReadable( true ); typedAttr.setStorable( false ); status = addAttribute( _outBody ); NM_CheckMStatus(status, "ERROR adding outBody attribute.\n"); // Create the attribute for the body name _bodyName = typedAttr.create( "bodyName", "bn", MFnData::kString ,stringData.create( MString("mesh-body") ), &status); NM_CheckMStatus( status, "Failed to create bodyName attribute"); typedAttr.setStorable( true ); typedAttr.setArray( false ); status = addAttribute( _bodyName ); NM_CheckMStatus( status, "Failed to add bodyName plug"); //Tesselation settings _subDivide = numAttr.create( "subDivide", "td", MFnNumericData::kInt , 0, &status); NM_CheckMStatus( status, "Failed to create subDivide attribute"); numAttr.setStorable( true ); numAttr.setArray( false ); status = addAttribute( _subDivide ); NM_CheckMStatus( status, "Failed to add bodyName plug"); // Attribute affects attributeAffects( _bodyName, _outBody ); attributeAffects( _subDivide, _outBody ); attributeAffects( _inSurface, _outBody ); attributeAffects( _useTransform, _outBody ); attributeAffects( _inTransform, _outBody ); return MS::kSuccess; }
// In order for the new animation curve positions to match the controller's previous global position, // first we need to get the controller's global transform matrix. The new local position of the controller // will be the controller's global transform matrix multiplied by the inverse of the new parent group's // global transform matrix. // So if: // [A] = controller's global transformation matrix // [B] = parent group's global transformation matrix // [X] = controller's new local transformation matrix // Then: // [X] = [A]inverse([B]) // // The controller's new local transformation matrix needs to be calculated per keyframe, which is why // a map of world position matrices for the controller are passed in as a parameter. The key for the map // is the time at which the associated world matrix was stored. MStatus lrutils::updateAnimCurves(MObject transformObj, std::map<double, MMatrix> ctlWorldMatrices, MMatrix ctlGroupMatrix) { MStatus status = MS::kFailure; MFnTransform transformFn( transformObj, &status ); MyCheckStatusReturn(status, status.errorString() ); //get all of the connections from the transform node MPlugArray transformConnections; status = transformFn.getConnections( transformConnections ); MyCheckStatusReturn(status, status.errorString() ); for(unsigned int i = 0; i < transformConnections.length(); i++) { //get all of the plugs this plug is connected to as a destination MPlugArray connectedPlugs; transformConnections[i].connectedTo(connectedPlugs,true,false,&status); MyCheckStatusReturn(status, status.errorString() ); MString plugName = transformConnections[i].partialName(false,false,false,false,false,true); for(unsigned int j = 0; j < connectedPlugs.length(); j++) { MObject connectedObj = connectedPlugs[j].node(); MFn::Type animType = connectedObj.apiType(); //if the connected object is an animCurveT[L,A], then transform it if( (animType == MFn::kAnimCurveTimeToDistance) || (animType == MFn::kAnimCurveTimeToAngular) ) { MFnAnimCurve animCurve(connectedObj, &status); MyCheckStatusReturn(status, status.errorString() ); //iterate through every key in the curve for(unsigned int k = 0; k < animCurve.numKeys(); k++) { double keyTime = animCurve.time(k, &status).value(); MyCheckStatusReturn( status, status.errorString() ); double keyVal = animCurve.value(k, &status); MyCheckStatusReturn( status, status.errorString() ); float tangentX, tangentY; status = animCurve.getTangent(k, tangentX, tangentY, false); MyCheckStatusReturn(status, status.errorString() ); //stringstream tmp; //tmp << "out tangent = (" << tangentX << "," << tangentY << ")"; //MGlobal::displayInfo(tmp.str().c_str()); //calculate the controller's local transformation matrix //first retrieve the corresponding world matrix for this key time MMatrix ctlWorldMatrix = ctlWorldMatrices[keyTime]; //if the transformation matrices are the same, don't update the curve //if( ctlWorldMatrix == ctlGroupMatrix) { // continue; //} MTransformationMatrix ctlGroupTransMatrix(ctlGroupMatrix); MMatrix ctlGroupMatrixInverse = ctlGroupTransMatrix.asMatrixInverse(); MMatrix newCtlLocalMatrix = ctlWorldMatrix * ctlGroupMatrixInverse; MTransformationMatrix newCtlLocalTransMatrix(newCtlLocalMatrix); //determine if the curve is for translation data if(animType == MFn::kAnimCurveTimeToDistance) { MVector vTransform = newCtlLocalTransMatrix.translation(MSpace::kTransform); if( plugName.indexW( MString("X") ) != -1 ) { keyVal = vTransform.x; } else if ( plugName.indexW( MString("Y") ) != -1 ) { keyVal = vTransform.y; } else if ( plugName.indexW( MString("Z") ) != -1 ) { keyVal = vTransform.z; } //if the curve is for rotation data } else if (animType == MFn::kAnimCurveTimeToAngular) { double* rotation = new double[3]; MTransformationMatrix::RotationOrder rotOrder = MTransformationMatrix::kXYZ; newCtlLocalTransMatrix.getRotation(rotation,rotOrder); if( plugName.indexW( MString("X") ) != -1 ) { keyVal = rotation[0]; } else if ( plugName.indexW( MString("Y") ) != -1 ) { keyVal = rotation[1]; } else if ( plugName.indexW( MString("Z") ) != -1 ) { keyVal = rotation[2]; } } animCurve.setValue(k, keyVal); status = MS::kSuccess; } } } } return status; }
MStatus boingRbCmd::redoIt() { if (argParser->isFlagSet("help") || argParser->isFlagSet("h")) { MString helpMsg = "boingRB - command : Boing - bullet plugin by Risto Puukko\n"; helpMsg += "---------------------------------------------------------\n"; helpMsg += "boingRB [flag] [args] \n"; helpMsg += "\n"; helpMsg += "flags :\n"; helpMsg += " -getAttr [name.attr]\n"; helpMsg += " example : boingRb -getAttr (\"boingRb1.velocity\");\n" ; helpMsg += "\n"; helpMsg += " -getAttr [*.attr]\n"; helpMsg += " example : boingRb -getAttr (\"*.name\");\n" ; helpMsg += "\n"; helpMsg += " -setAttr [name.attr] -value [float float float ]\n"; helpMsg += " example : boingRb -setAttr (\"boingRb1.velocity\") -value 0 4 3 ;\n" ; helpMsg += "\n"; helpMsg += " -addAttr [name.attr] -type [int/double/string/vector]\n"; helpMsg += " example : boingRb -addAttr \"sampleRb.IntAttribute\" -type \"int\";\n" ; helpMsg += " example : boingRb -addAttr \"sampleRb.VectorAttribute\" -type \"vector\";\n" ; helpMsg += "\n"; helpMsg += " -create [ ( \"name=string;geo=string;velocity/vel=float,float,float;position/pos=float,float,float\" )]\n"; helpMsg += " example : boingRb -create (\"name=sampleRb;geo=pCubeShape1;pos=0,4,0\");\n"; helpMsg += "\n"; helpMsg += " -exists [name]\n"; helpMsg += " example : boingRb -exists \"sampleRb\";\n" ; helpMsg += "\n"; helpMsg += " -delete [name]\n"; helpMsg += " example : boingRb -delete \"sampleRb\";\n"; helpMsg += "\n"; helpMsg += "---------------------------------------------------------\n"; MGlobal::displayInfo(helpMsg); return MS::kSuccess; } isSetAttr = argParser->isFlagSet("-setAttr"); isGetAttr = argParser->isFlagSet("-getAttr"); isAddAttr = argParser->isFlagSet("-addAttr"); isType = argParser->isFlagSet("-type"); isExists = argParser->isFlagSet("-exists"); isAttributeExist = argParser->isFlagSet("-attributeExist"); isCreate = argParser->isFlagSet("-create"); isDelete = argParser->isFlagSet("-delete"); isValue = argParser->isFlagSet("-value"); //std::cout<<"argsList : "<<*argsList<<std::endl; //unsigned i; //MStatus stat; //MVector res; // Parse the arguments. /* for (i = 0; i <argsList->length (); i++) { //MString arg = argsList->asString(i, &stat); //if (MS::kSuccess == stat) std::cout<<"arg["<<i<<"] : "<<arg<<std::endl; if ( MString ("-setAttr") == argsList->asString(i, &stat) && MString ("-value") == argsList->asString(i+2, &stat) && MS::kSuccess == stat ) { for (unsigned j=3; j!=6; ++j) res[j-3 ] = argsList->asDouble (j, &stat); } } std::cout<<"res : "<<res<<std::endl; */ if (isSetAttr && isValue) { MString sAttr; argParser->getFlagArgument("setAttr", 0, sAttr); //std::cout<<sAttr<<std::endl; MStringArray jobArgsArray = parseArguments(sAttr, "."); MString rbName = jobArgsArray[0]; MString attr = checkAttribute(jobArgsArray[1]); //std::cout<<"attr : "<<attr<<std::endl; if ( attr == "custom" ) { MString customAttr = jobArgsArray[1]; //char * custAttr = (char*)customAttr.asChar(); //std::cout<<"customAttr : "<<customAttr<<std::endl; shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node(); bSolverNode::m_custom_data *data = b_solv->getdata(rbName); //std::cout<<"data : "<<data<<std::endl; if (!data) return MS::kFailure; //std::cout<<"data->m_int_data : "<<data->m_int_data<<std::endl; MString type = b_solv->getAttrType(data, customAttr); //std::cout<<"attrype : "<<type<<std::endl; if (type == "string") { //std::cout<<"saving custom string : "<<customAttr<<std::endl; MString value; value = argsList->asString(3); data->m_string_data.append(value); b_solv->set_custom_data_string(data, customAttr, value); //data->m_attr_type.append(customAttr); //char * chars = (char *)value.asChar(); //void * char_ptr = (void *)chars; //b_solv->set_custom_data(customAttr, char_ptr); } else if (type == "double") { //std::cout<<"saving custom double : "<<customAttr<<std::endl; double value; value = argsList->asDouble(3); data->m_double_data.append(value); b_solv->set_custom_data_double(data, customAttr, value); //data->m_attr_type.append(customAttr); //void *val = &value; //b_solv->set_custom_data(customAttr, val); } else if (type == "int") { //std::cout<<"saving custom int : "<<customAttr<<std::endl; int value; value = argsList->asInt(3); //std::cout<<"argsList->get(3, value) -> value : "<<value<<std::endl; data->m_int_data.append(value); b_solv->set_custom_data_int(data, customAttr, value); //data->m_attr_type.append(customAttr); //std::cout<<"data->m_int_data : "<<data->m_int_data<<std::endl; //void *val = &value; //b_solv->set_custom_data(customAttr, val); //std::cout<<"b_solv->set_custom_data,static_cast<void*>(&value)) DONE!!!"<<std::endl; } else if (type == "vector") { //std::cout<<"saving custom vector : "<<customAttr<<std::endl; MVector value = MVector(); value.x = argsList->asDouble(3); value.y = argsList->asDouble(4); value.z = argsList->asDouble(5); data->m_vector_data.append(value); b_solv->set_custom_data_vector(data, customAttr, value); //data->m_attr_type.append(customAttr); //MVector *MVecPtr = &value; //void * vec_ptr = static_cast<void*const>(MVecPtr); //b_solv->set_custom_data(customAttr, vec_ptr); } } else { if (attr == "velocity" || attr == "position" || attr == "angularVelocity") { MVector value; value.x = argsList->asDouble(3); value.y = argsList->asDouble(4); value.z = argsList->asDouble(5); //std::cout<<"vector argument : "<<value<<std::endl; setBulletVectorAttribute(rbName, attr, value); } } //cout<<value<<endl; setResult(MS::kSuccess); } else if ( isAttributeExist ) { MString exAttr; bool result = false; argParser->getFlagArgument("attributeExist", 0, exAttr); //std::cout<<"exAttr : "<<exAttr<<std::endl; MStringArray jobArgsArray = parseArguments(exAttr, "."); MString rbname = jobArgsArray[0]; //std::cout<<"rbname : "<<rbname<<std::endl; MString attrToQuery = jobArgsArray[1]; //std::cout<<"attrToQuery : "<<attrToQuery<<std::endl; MString attr = checkAttribute(attrToQuery); //std::cout<<"attr : "<<attr<<std::endl; if ( attr == "custom" ){ // here we check if user attribute by the name attrToQuery exists shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node(); //char * queryAttr = (char*)attrToQuery.asChar(); MString attrResult = b_solv->getAttrType(b_solv->getdata(rbname), attrToQuery); if (attrResult != "") //if (b_solv->attribute_exists(attrToQuery)) result = true; //std::cout<<result<<std::endl;; setResult(result); } } else if ( isAddAttr && isType ) { MString aAttr; argParser->getFlagArgument("addAttr", 0, aAttr); //std::cout<<"aAttr : "<<aAttr<<std::endl; MStringArray jobArgsArray = parseArguments(aAttr, "."); //std::cout<<"jobArgsArray : "<<jobArgsArray<<std::endl; MString rbname = jobArgsArray[0]; MString attrAdded = jobArgsArray[1]; //char *added = (char *)attrAdded.asChar(); MString attrType; argParser->getFlagArgument("-type", 0, attrType); //char *type = (char *)attrType.asChar(); //std::cout<<"attrType : "<<attrType<<std::endl; shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node(); bSolverNode::m_custom_data *data = b_solv->getdata(rbname); data->m_attr_name.append(attrAdded); data->m_attr_type.append(attrType); b_solv->saveAttrType(data, attrAdded, attrType); //std::cout<<"attr "<<aAttr<<" added"<<std::endl; //std::cout<<"data->m_attr_type : "<<data->m_attr_type<<std::endl; //std::cout<<"data->m_attr_name : "<<data->m_attr_name<<std::endl; } else if ( isGetAttr) { MString gAttr; shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node(); argParser->getFlagArgument("getAttr", 0, gAttr); //std::cout<<gAttr<<std::endl; MStringArray jobArgsArray = parseArguments(gAttr, "."); MString rbname = jobArgsArray[0]; //std::cout<<"name : "<<rbname<<std::endl; if ( rbname == "" ) { MString errorMsg = "ERROR ! boing -getAttr must provide a rigid body name!"; displayWarning(errorMsg, true); return MS::kFailure; } MString attr = checkAttribute(jobArgsArray[1]); //std::cout<<"attr = "<<attr<<std::endl; if ( attr=="velocity" || attr=="position" || attr=="angularVelocity" ) { //MVector result = MDoubleArray dResult = getBulletVectorAttribute(rbname, attr); setResult(dResult); } else if (attr == "contactPositions") { bSolverNode::m_custom_data *data = b_solv->getdata(rbname); MDoubleArray d_points = MDoubleArray(); if ( data->m_contact_count > 0 ) { MPointArray points = data->m_contact_positions; for (int i=0; i<points.length();i++) { d_points.append(points[i].x); d_points.append(points[i].y); d_points.append(points[i].z); } } setResult(d_points); } else if (attr == "contactGeos") { MStringArray contact_objects = MStringArray(); bSolverNode::m_custom_data *data = b_solv->getdata(rbname); if ( data->m_contact_count > 0 ) { MStringArray contact_objects = data->m_contact_objects; } setResult(contact_objects); } else if (attr == "contactCount") { bSolverNode::m_custom_data *data = b_solv->getdata(rbname); int contact_count = data->m_contact_count; setResult(contact_count); } else if (attr == "name") { MStringArray result; MStringArray names = b_solv->get_all_keys(); //std::cout<<"names : "<<names<<std::endl; //std::cout<<"b_solv->getdatalength() : "<<b_solv->getdatalength()<<std::endl; for(int i=0; i < names.length(); i++) { bSolverNode::m_custom_data *data = b_solv->getdata(names[i]); if ( NULL != data) { //std::cout<<"data->name : "<<data->name<<std::endl; //std::cout<<"data->m_initial_position: "<<data->m_initial_position<<std::endl; result.append(data->name); } } setResult(result); } else if ( attr == "" ) { MString errorMsg = "ERROR ! boing -getAttr must provide an attribute name to query!"; displayWarning(errorMsg, true); return MS::kFailure; } else if ( attr == "custom" ){ // here we handle user attributes MString customAttr = jobArgsArray[1]; //char * custAttr = (char*)customAttr.asChar(); //std::cout<<"customAttr : "<<customAttr<<std::endl; MString type = b_solv->getAttrType(b_solv->getdata(rbname), customAttr); //bSolverNode::m_custom_data *data = b_solv->getdata(rbname); std::cout<<" type : "<<type<<std::endl; if (type == "string") { //char * result = static_cast<char*>(b_solv->get_custom_data(customAttr)); MString result = b_solv->get_custom_data_string(b_solv->getdata(rbname), customAttr); if (result != NULL) { //std::cout<<"result : "<<result<<std::endl; MString value(result); setResult(value); } else { displayError(MString("Error getting b_solv->get_custom_data_string(\"" + customAttr + "\")")); } } else if (type == "double") { //double *value = static_cast<double*>(b_solv->get_custom_data(customAttr)); double value = b_solv->get_custom_data_double(b_solv->getdata(rbname), customAttr); setResult(value); } else if (type == "int") { //int *value = static_cast<int*>(b_solv->get_custom_data(customAttr)); int value = b_solv->get_custom_data_int(b_solv->getdata(rbname), customAttr); setResult(value); } else if (type == "vector") { //void * result = b_solv->get_custom_data(customAttr); //MVector *vec_res = (MVector*)result; MVector result = b_solv->get_custom_data_vector(b_solv->getdata(rbname), customAttr); MDoubleArray value; value.append(result.x); value.append(result.y); value.append(result.z); setResult(value); } } } else if ( isCreate ) { MString aArgument; argParser->getFlagArgument("-create", 0, aArgument); MStringArray createArgs = parseArguments(aArgument,";"); int size = createArgs.length(); MString inputShape; MString rbname = "dummyRb"; MVector av; MVector vel; MVector pos; MVector rot; for (int i=0; i!=size; ++i) { MStringArray singleArg = parseArguments(createArgs[i],"="); //std::cout<<"singleArg : "<<singleArg<<std::endl; if (singleArg[0] == "name") { rbname = singleArg[1]; } else if (singleArg[0] == "geo") { //geo inputShape = singleArg[1]; //std::cout<<"geo = "<<inputShape<<std::endl; } else if (singleArg[0] == "vel") { //initialvelocity MStringArray velArray = parseArguments(singleArg[1], ","); vel = MVector(velArray[0].asDouble(), velArray[1].asDouble(), velArray[2].asDouble() ); //std::cout<<"velocity = "<<vel<<std::endl; } else if (singleArg[0] == "pos") { //initialposition MStringArray posArray = parseArguments(singleArg[1], ","); pos = MVector(posArray[0].asDouble(), posArray[1].asDouble(), posArray[2].asDouble() ); //std::cout<<"position = "<<pos<<std::endl; } else if (singleArg[0] == "rot") { //initialrotation MStringArray rotArray = parseArguments(singleArg[1], ","); rot = MVector(rotArray[0].asDouble(), rotArray[1].asDouble(), rotArray[2].asDouble() ); //std::cout<<"rotation = "<<rot<<std::endl; } else if (singleArg[0] == "av") { //initialAngularVelocity MStringArray avArray = parseArguments(singleArg[1], ","); av = MVector(avArray[0].asDouble(), avArray[1].asDouble(), avArray[2].asDouble() ); //std::cout<<"initialAngularVelocity = "<<av<<std::endl; } else { std::cout<<"Unrecognized parameter : "<<singleArg[0]<<std::endl; } } // create boing node shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node(); MObject node = nameToNode(inputShape); float mass = 1.0f; MString tname = "boing"; MStatus stat = b_solv->createNode(node, rbname, tname, pos, vel, rot, av, mass); if (MS::kSuccess == stat) { setResult(rbname); } else { MGlobal::displayError(MString("Something went wrong when trying to create rigidbody : " + rbname + " .")); } } else if ( isDelete ) { MString aArgument; argParser->getFlagArgument("-delete", 0, aArgument); //std::cout<<"delete aArgument "<<aArgument<<std::endl; if (aArgument != "") { shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node(); b_solv->deletedata(aArgument); MStatus stat = b_solv->delete_key(aArgument, -1); if (stat != MS::kSuccess) { std::cerr<<"error occurred deleting "<<aArgument<<" ."<<std::endl; setResult(1); } } } else if ( isExists ) { MString exArg; argParser->getFlagArgument("-exists", 0, exArg); //std::cout<<"exArg : "<<exArg<<std::endl; if (exArg != "") { shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node(); bSolverNode::m_custom_data *data = b_solv->getdata(exArg); int result = false; if ( NULL != data ) { //setResult ( data->name ); result = true; } setResult(result); } } return MS::kSuccess; }
int MHL7DomainXlate::translatePDQQPD3(const MString& s, MPatient& patient) const { MLogClient logClient; logClient.log(MLogClient::MLOG_VERBOSE, "","MHL7DomainXlate::translatepdQQPD3", __LINE__, "Enter method"); MString queryString = s; int idx = 0; MString firstName = ""; MString lastName = ""; MString patientID = ""; MString dateOfBirth = ""; while (queryString.tokenExists('~', idx)) { MString x = queryString.getToken('~', idx); // cout << idx << ":" << x << endl; logClient.logTimeStamp(MLogClient::MLOG_VERBOSE, MString("Next token from query: ") + x); MString headerCharacter = x.subString(0, 1); if (headerCharacter != "@") { continue; } MString x1 = x.subString(1, 0); if (!x1.tokenExists('^', 1)) { continue; } MString fieldName = x1.getToken('^', 0); MString fieldValue= x1.getToken('^', 1); MString debugString = MString("Field Name: ") + fieldName + " Field Value: " + fieldValue; logClient.logTimeStamp(MLogClient::MLOG_VERBOSE, debugString); // cout << "Field Name: " << fieldName << endl; // cout << "Field Value: " << fieldValue << endl; idx++; if (fieldName == "PID.5.1.1") { lastName = fieldValue; } else if (fieldName == "PID.5.2") { firstName = fieldValue; } else if (fieldName == "PID.3.1") { patientID = fieldValue; } else if (fieldName == "PID.7.1") { dateOfBirth = fieldValue; } } if (lastName == "" && firstName == "") { } else if (firstName == "") { patient.patientName(lastName + MString("%")); } else if (lastName == "") { patient.patientName(MString("%^") + firstName); } else { patient.patientName(lastName + MString("%^") + firstName + MString("%")); } patient.patientID(patientID); patient.dateOfBirth(dateOfBirth); logClient.log(MLogClient::MLOG_VERBOSE, "","MHL7DomainXlate::translatepdQQPD3", __LINE__, "Exit method"); return 0; }
MString getTexMap(std::string att) { return MString(texObjMap[att].c_str()); }
MStatus progressWindowPlugin::doIt(const MArgList &args) { MStatus stat = MS::kSuccess; MString title = "Doing Nothing"; MString sleeping = "Sleeping: "; int amount = 0; int maxProgress = 10; // First reserve the progress window. If a progress window is already // active (eg. through the mel "progressWindow" command), this command // fails. // if (!MProgressWindow::reserve()) { MGlobal::displayError("Progress window already in use."); stat = MS::kFailure; return stat; } // // Set up and print progress window state // CHECK_MSTATUS(MProgressWindow::setProgressRange(amount, maxProgress)); CHECK_MSTATUS(MProgressWindow::setTitle(title)); CHECK_MSTATUS(MProgressWindow::setInterruptable(true)); CHECK_MSTATUS(MProgressWindow::setProgress(amount)); MString progressWindowState = MString("Progress Window Info:") + MString("\nMin: ") + MProgressWindow::progressMin() + MString("\nMax: ") + MProgressWindow::progressMax() + MString("\nTitle: ") + MProgressWindow::title() + MString("\nInterruptible: ") + MProgressWindow::isInterruptable(); MGlobal::displayInfo(progressWindowState); CHECK_MSTATUS(MProgressWindow::startProgress()); // Count 10 seconds // for (int i = amount; i < maxProgress; i++) { if (i != 0 && MProgressWindow::isCancelled()) { MGlobal::displayInfo("Progress interrupted!"); break; } MString statusStr = sleeping; statusStr += i; CHECK_MSTATUS(MProgressWindow::setProgressStatus(statusStr)); CHECK_MSTATUS(MProgressWindow::advanceProgress(1)); MGlobal::displayInfo(MString("Current progress: ") + MProgressWindow::progress()); MGlobal::executeCommand("pause -sec 1", false, false); } // End the progress, unreserving the progress window so it can be used // elsewhere. // CHECK_MSTATUS(MProgressWindow::endProgress()); return stat; }
MString getType(std::string att) { return MString(typeMap[att].c_str()); }
MString getParamName(std::string att) { return MString(paramNameMap[att].c_str()); }
MStatus bruiseMapNode::initialize() { MStatus status; MFnNumericAttribute nAttr; MFnTypedAttribute tAttr; aBias = nAttr.create("bias", "bs", MFnNumericData::kFloat, 0.1f, &status); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable(true)); CHECK_MSTATUS( nAttr.setKeyable(true)); CHECK_MSTATUS( nAttr.setMin(0.f)); amapsize = nAttr.create( "mapsize", "mapsize", MFnNumericData::kInt, 1024 ); nAttr.setStorable(false); nAttr.setKeyable(false); addAttribute( amapsize ); auvset = tAttr.create("uvset", "uv", MFnData::kString, MObject::kNullObj, &status); CHECK_MSTATUS( status ); CHECK_MSTATUS( tAttr.setStorable(true)); CHECK_MSTATUS( tAttr.setKeyable(false)); tAttr.setCached( true ); tAttr.setInternal( true ); zWorks::createMatrixAttr(aworldSpace, "worldSpace", "ws"); aoutput = nAttr.create( "outval", "ov", MFnNumericData::kInt, 1 ); nAttr.setStorable(false); nAttr.setWritable(false); nAttr.setKeyable(false); addAttribute( aoutput ); zWorks::createTypedAttr(agrowth, MString("growMesh"), MString("gm"), MFnData::kMesh); zCheckStatus(addAttribute(agrowth), "ERROR adding grow mesh"); zWorks::createTypedAttr(aguide, MString("guideMesh"), MString("gdm"), MFnData::kMesh); zCheckStatus(addAttribute(aguide), "ERROR adding grow mesh"); astartframe = nAttr.create( "startFrame", "sf", MFnNumericData::kInt, 1 ); nAttr.setStorable(true); nAttr.setKeyable(true); addAttribute( astartframe ); zWorks::createTimeAttr(acurrenttime, MString("currentTime"), MString("ct"), 1.0); zCheckStatus(addAttribute(acurrenttime), "ERROR adding time"); asavemap = nAttr.create( "saveMap", "sm", MFnNumericData::kInt, 0); nAttr.setStorable(false); nAttr.setKeyable(true); addAttribute(asavemap); CHECK_MSTATUS( addAttribute(aBias)); CHECK_MSTATUS( addAttribute(auvset)); addAttribute(aworldSpace); attributeAffects( aBias, aoutput ); attributeAffects( amapsize, aoutput ); attributeAffects( agrowth, aoutput ); attributeAffects( astartframe, aoutput ); attributeAffects( acurrenttime, aoutput ); attributeAffects( aguide, aoutput ); attributeAffects( asavemap, aoutput ); return MS::kSuccess; }
namespace AbcImportStrings { #define kPluginId "AbcImport" const MStringResourceId kErrorInvalidAlembic ( kPluginId, "kErrorInvalidAlembic", MString( "is not a valid Alembic file" ) ); const MStringResourceId kErrorConnectionNotFound ( kPluginId, "kErrorConnectionNotFound", MString( "not found for connection" ) ); const MStringResourceId kErrorConnectionNotMade ( kPluginId, "kErrorConnectionNotMade", MString( "connection not made" ) ); const MStringResourceId kWarningNoAnimatedParticleSupport ( kPluginId, "kWarningNoAnimatedParticleSupport", MString( "Currently no support for animated particle system" ) ); const MStringResourceId kWarningUnsupportedAttr ( kPluginId, "kWarningUnsupportedAttr", MString( "Unsupported attr, skipping: " ) ); const MStringResourceId kWarningSkipIndexNonArray ( kPluginId, "kWarningSkipIndexNonArray", MString( "Skipping indexed or non-array property: " ) ); const MStringResourceId kWarningSkipOddlyNamed ( kPluginId, "kWarningSkipOddlyNamed", MString( "Skipping oddly named property: " ) ); const MStringResourceId kWarningSkipNoSamples ( kPluginId, "kWarningSkipNoSamples", MString( "Skipping property with no samples: " ) ); const MStringResourceId kAEAlembicAttributes ( kPluginId, "kAEAlembicAttributes", MString( "Alembic Attributes" ) ); }
//------------------------------------------------------------------------------ // bool LocatorRepresentation::activate() { MPxAssembly* const assembly = getAssembly(); // Create a locator node, and parent it to our container. MDagModifier dagMod; MStatus status; dagMod.createNode(MString("locator"), assembly->thisMObject(), &status); if (status != MStatus::kSuccess) { return false; } status = dagMod.doIt(); if (status != MStatus::kSuccess) { return false; } // If we have annotation text, create an annotation shape, and a // transform for it. Parent the annotation transform to the assembly. if (fAnnotation.numChars() > 0) { MObject transformObj = dagMod.createNode( MString("transform"), assembly->thisMObject(), &status); if (status != MStatus::kSuccess) { return false; } MString annotationName = "annotation"; // the + "#" forces Maya to rename using integers for unique names MString transformName = annotationName + "#"; dagMod.renameNode(transformObj, transformName); status = dagMod.doIt(); if (status != MStatus::kSuccess) { return false; } MObject annotationObj = dagMod.createNode( MString("annotationShape"), transformObj, &status); if (status != MStatus::kSuccess) { return false; } status = dagMod.doIt(); if (status != MStatus::kSuccess) { return false; } // Set the annotation text. MFnDependencyNode annotation(annotationObj); MPlug text = annotation.findPlug(MString("text"), true, &status); if (status != MStatus::kSuccess) { return false; } text.setValue(fAnnotation); // Get rid of the arrow: our annotation doesn't need to be // offset from the locator for readability, since the locator // has no volume. Therefore, we don't need an arrow to point // from the annotation back to the object. MPlug displayArrow = annotation.findPlug(MString("displayArrow"), true, &status); if (status != MStatus::kSuccess) { return false; } displayArrow.setValue(false); } return status == MStatus::kSuccess; }
MString mt@_RenderGlobals::getImageExt() { return MString("ext"); }
MStatus particlePathsCmd::doIt( const MArgList& args ) { MStatus stat = parseArgs( args ); if( stat != MS::kSuccess ) { return stat; } MFnParticleSystem cloud( particleNode ); if( ! cloud.isValid() ) { MGlobal::displayError( "The function set is invalid!" ); return MS::kFailure; } // // Create curves from the particle system in two stages. First, sample // all particle positions from the start time to the end time. Then, // use the data that was collected to create curves. // // Create the particle hash table at a fixed size. This should work fine // for small particle systems, but may become inefficient for larger ones. // If the plugin is running very slow, increase the size. The value should // be roughly the number of particles that are expected to be emitted // within the time period. // ParticleIdHash hash(1024); MIntArray idList; // // Stage 1 // MVectorArray positions; MIntArray ids; int i = 0; for (double time = start; time <= finish + TOLERANCE; time += increment) { MTime timeSeconds(time,MTime::kSeconds); // It is necessary to query the worldPosition attribute to force the // particle positions to update. // cloud.evaluateDynamics(timeSeconds,false); // MGlobal::executeCommand(MString("getAttr ") + cloud.name() + // MString(".worldPosition")); if (!cloud.isValid()) { MGlobal::displayError( "Particle system has become invalid." ); return MS::kFailure; } MGlobal::displayInfo( MString("Received ") + (int)(cloud.count()) + " particles, at time " + time); // Request position and ID data for particles // cloud.position( positions ); cloud.particleIds( ids ); if (ids.length() != cloud.count() || positions.length() != cloud.count()) { MGlobal::displayError( "Invalid array sizes." ); return MS::kFailure; } for (int j = 0; j < (int)cloud.count(); j++) { // Uncomment to show particle positions as the plugin accumulates // samples. /* MGlobal::displayInfo(MString("(") + (positions[j])[0] + MString(",") + (positions[j])[1] + MString(",") + (positions[j])[2] + MString(")")); */ MPoint pt(positions[j]); if (hash.getPoints(ids[j]).length() == 0) { idList.append(ids[j]); } hash.insert(ids[j],pt); } i++; } // // Stage 2 // for (i = 0; i < (int)(idList.length()); i++) { MPointArray points = hash.getPoints(idList[i]); // Don't bother with single samples if (points.length() <= 1) { continue; } // Add two additional points, so that the curve covers all sampled // values. // MPoint p1 = points[0]*2 - points[1]; MPoint p2 = points[points.length()-1]*2 - points[points.length()-2]; points.insert(p1,0); points.append(p2); // Uncomment to show information about the generated curves /* MGlobal::displayInfo( MString("ID ") + (int)(idList[i]) + " has " + (int)(points.length()) + " curve points."); for (int j = 0; j < (int)(points.length()); j++) { MGlobal::displayInfo(MString("(") + points[j][0] + MString(",") + points[j][1] + MString(",") + points[j][2] + MString(")")); } */ MDoubleArray knots; knots.insert(0.0,0); for (int j = 0; j < (int)(points.length()); j++) { knots.append((double)j); } knots.append(points.length()-1); MStatus status; MObject dummy; MFnNurbsCurve curve; curve.create(points,knots,3,MFnNurbsCurve::kOpen,false,false,dummy,&status); if (!status) { MGlobal::displayError("Failed to create nurbs curve."); return MS::kFailure; } } return MS::kSuccess; }
bool mt@_RenderGlobals::getMt@Globals() { logger.debug("mt@_RenderGlobals::get@Globals"); MSelectionList @GlobalsList; @GlobalsList.add("@Globals"); if( @GlobalsList.length() == 0 ) { logger.debug("@Globals not found. Stopping."); return false; } MObject node; @GlobalsList.getDependNode(0, node); MFnDependencyNode @Globals(node); renderGlobalsMobject = node; try{ if(!getInt(MString("translatorVerbosity"), @Globals, this->translatorVerbosity)) throw("problem reading @Globals.translatorVerbosity"); switch(this->translatorVerbosity) { case 0: logger.setLogLevel(Logging::Info); break; case 1: logger.setLogLevel(Logging::Error); break; case 2: logger.setLogLevel(Logging::Warning); break; case 3: logger.setLogLevel(Logging::Progress); break; case 4: logger.setLogLevel(Logging::Debug); break; } // ------------- automatically created attributes start ----------- // // ------------- automatically created attributes end ----------- // if(!getInt(MString("filtertype"), @Globals, this->filterType)) throw("problem reading @Globals.filtertype"); if(!getFloat(MString("filtersize"), @Globals, this->filterSize)) throw("problem reading @Globals.filtersize"); if(!getFloat(MString("gamma"), @Globals, this->gamma)) throw("problem reading @Globals.gamma"); if(!getInt(MString("samplesX"), @Globals, this->samplesX)) throw("problem reading @Globals.samplesX"); if(!getInt(MString("samplesY"), @Globals, this->samplesY)) throw("problem reading @Globals.samplesY"); if(!getInt(MString("minSamples"), @Globals, this->minSamples)) throw("problem reading @Globals.minSamples"); if(!getInt(MString("maxSamples"), @Globals, this->maxSamples)) throw("problem reading @Globals.maxSamples"); if(!getInt(MString("bitdepth"), @Globals, this->bitdepth)) throw("problem reading @Globals.bitdepth"); if(!getInt(MString("translatorVerbosity"), @Globals, this->translatorVerbosity)) throw("problem reading @Globals.translatorVerbosity"); if(!getInt(MString("rendererVerbosity"), @Globals, this->rendererVerbosity)) throw("problem reading @Globals.rendererVerbosity"); if(!getInt(MString("tilesize"), @Globals, this->tilesize)) throw("problem reading @Globals.tilesize"); if(!getInt(MString("threads"), @Globals, this->threads)) throw("problem reading @Globals.threads"); if(!getInt(MString("geotimesamples"), @Globals, this->geotimesamples)) throw("problem reading @Globals.geotimesamples"); if(!getInt(MString("xftimesamples"), @Globals, this->xftimesamples)) throw("problem reading @Globals.xftimesamples"); if(!getInt(MString("maxTraceDepth"), @Globals, this->maxTraceDepth)) throw("problem reading @Globals.maxTraceDepth"); if(!getBool(MString("createDefaultLight"), @Globals, this->createDefaultLight)) throw("problem reading @Globals.createDefaultLight"); if(!getBool(MString("detectShapeDeform"), @Globals, this->detectShapeDeform)) throw("problem reading @Globals.detectShapeDeform"); if(!getString(MString("optimizedTexturePath"), @Globals, this->optimizedTexturePath)) throw("problem reading @Globals.optimizedTexturePath"); if(!getString(MString("basePath"), @Globals, this->basePath)) throw("problem reading @Globals.basePath"); if(!getString(MString("imagePath"), @Globals, this->imagePath)) throw("problem reading @Globals.imagePath"); int id = 0; if(!getEnum(MString("imageFormat"), @Globals, id, this->imageFormatString)) throw("problem reading @Globals.imageFormat"); if(!getBool(MString("exportSceneFile"), @Globals, this->exportSceneFile)) throw("problem reading @Globals.exportSceneFile"); if(!getString(MString("exportSceneFileName"), @Globals, this->exportSceneFileName)) throw("problem reading @Globals.exportSceneFileName"); if(!getString(MString("imageName"), @Globals, this->imageName)) throw("problem reading @Globals.imageName"); if(!getBool(MString("adaptiveSampling"), @Globals, this->adaptiveSampling)) throw("problem reading @Globals.adaptiveSampling"); if(!getBool(MString("doMotionBlur"), @Globals, this->doMb)) throw("problem reading @Globals.doMotionBlur"); if(!getBool(MString("doDof"), @Globals, this->doDof)) throw("problem reading @Globals.doDof"); if(!getFloat(MString("sceneScale"), @Globals, this->sceneScale)) throw("problem reading @Globals.sceneScale"); this->sceneScaleMatrix.setToIdentity(); this->sceneScaleMatrix.matrix[0][0] = this->sceneScale; this->sceneScaleMatrix.matrix[1][1] = this->sceneScale; this->sceneScaleMatrix.matrix[2][2] = this->sceneScale; }catch(char *errorMsg){ logger.error(errorMsg); this->good = false; return false; } return true; }
void NifMeshExporterSkyrim::ExportMesh( MObject dagNode ) { //out << "NifTranslator::ExportMesh {"; ComplexShape cs; MStatus stat; MObject mesh; //Find Mesh child of given transform object MFnDagNode nodeFn(dagNode); cs.SetName(this->translatorUtils->MakeNifName(nodeFn.name())); for (int i = 0; i != nodeFn.childCount(); ++i) { // get a handle to the child if (nodeFn.child(i).hasFn(MFn::kMesh)) { MFnMesh tempFn(nodeFn.child(i)); //No history items if (!tempFn.isIntermediateObject()) { //out << "Found a mesh child." << endl; mesh = nodeFn.child(i); break; } } } MFnMesh visibleMeshFn(mesh, &stat); if (stat != MS::kSuccess) { //out << stat.errorString().asChar() << endl; throw runtime_error("Failed to create visibleMeshFn."); } //out << visibleMeshFn.name().asChar() << ") {" << endl; MFnMesh meshFn; MObject dataObj; MPlugArray inMeshPlugArray; MPlug childPlug; MPlug geomPlug; MPlug inputPlug; // this will hold the returned vertex positions MPointArray vts; //For now always use the visible mesh meshFn.setObject(mesh); //out << "Use the function set to get the points" << endl; // use the function set to get the points stat = meshFn.getPoints(vts); if (stat != MS::kSuccess) { //out << stat.errorString().asChar() << endl; throw runtime_error("Failed to get points."); } //Maya won't store any information about objects with no vertices. Just skip it. if (vts.length() == 0) { MGlobal::displayWarning("An object in this scene has no vertices. Nothing will be exported."); return; } vector<WeightedVertex> nif_vts(vts.length()); for (int i = 0; i != vts.length(); ++i) { nif_vts[i].position.x = float(vts[i].x); nif_vts[i].position.y = float(vts[i].y); nif_vts[i].position.z = float(vts[i].z); } //Set vertex info later since it includes skin weights //cs.SetVertices( nif_vts ); //out << "Use the function set to get the colors" << endl; MColorArray myColors; meshFn.getFaceVertexColors(myColors); //out << "Prepare NIF color vector" << endl; vector<Color4> niColors(myColors.length()); for (unsigned int i = 0; i < myColors.length(); ++i) { niColors[i] = Color4(myColors[i].r, myColors[i].g, myColors[i].b, myColors[i].a); } cs.SetColors(niColors); // this will hold the returned vertex positions MFloatVectorArray nmls; //out << "Use the function set to get the normals" << endl; // use the function set to get the normals stat = meshFn.getNormals(nmls, MSpace::kTransform); if (stat != MS::kSuccess) { //out << stat.errorString().asChar() << endl; throw runtime_error("Failed to get normals"); } //out << "Prepare NIF normal vector" << endl; vector<Vector3> nif_nmls(nmls.length()); for (int i = 0; i != nmls.length(); ++i) { nif_nmls[i].x = float(nmls[i].x); nif_nmls[i].y = float(nmls[i].y); nif_nmls[i].z = float(nmls[i].z); } cs.SetNormals(nif_nmls); //out << "Use the function set to get the UV set names" << endl; MStringArray uvSetNames; MString baseUVSet; MFloatArray myUCoords; MFloatArray myVCoords; bool has_uvs = false; // get the names of the uv sets on the mesh meshFn.getUVSetNames(uvSetNames); vector<TexCoordSet> nif_uvs; //Record assotiation between name and uv set index for later map<string, int> uvSetNums; int set_num = 0; for (unsigned int i = 0; i < uvSetNames.length(); ++i) { if (meshFn.numUVs(uvSetNames[i]) > 0) { TexType tt; string set_name = uvSetNames[i].asChar(); if (set_name == "base" || set_name == "map1") { tt = BASE_MAP; } else if (set_name == "dark") { tt = DARK_MAP; } else if (set_name == "detail") { tt = DETAIL_MAP; } else if (set_name == "gloss") { tt = GLOSS_MAP; } else if (set_name == "glow") { tt = GLOW_MAP; } else if (set_name == "bump") { tt = BUMP_MAP; } else if (set_name == "decal0") { tt = DECAL_0_MAP; } else if (set_name == "decal1") { tt = DECAL_1_MAP; } else { tt = BASE_MAP; } //Record the assotiation uvSetNums[set_name] = set_num; //Get the UVs meshFn.getUVs(myUCoords, myVCoords, &uvSetNames[i]); //Make sure this set actually has some UVs in it. Maya sometimes returns empty UV sets. if (myUCoords.length() == 0) { continue; } //Store the data TexCoordSet tcs; tcs.texType = tt; tcs.texCoords.resize(myUCoords.length()); for (unsigned int j = 0; j < myUCoords.length(); ++j) { tcs.texCoords[j].u = myUCoords[j]; //Flip the V coords tcs.texCoords[j].v = 1.0f - myVCoords[j]; } nif_uvs.push_back(tcs); baseUVSet = uvSetNames[i]; has_uvs = true; set_num++; } } cs.SetTexCoordSets(nif_uvs); // this will hold references to the shaders used on the meshes MObjectArray Shaders; // this is used to hold indices to the materials returned in the object array MIntArray FaceIndices; //out << "Get the connected shaders" << endl; // get the shaders used by the i'th mesh instance // Assume this is not instanced for now // TODO support instancing properly stat = visibleMeshFn.getConnectedShaders(0, Shaders, FaceIndices); if (stat != MS::kSuccess) { //out << stat.errorString().asChar() << endl; throw runtime_error("Failed to get connected shader list."); } vector<ComplexFace> nif_faces; //Add shaders to propGroup array vector< vector<NiPropertyRef> > propGroups; for (unsigned int shader_num = 0; shader_num < Shaders.length(); ++shader_num) { //Maya sometimes lists shaders that are not actually attached to any face. Disregard them. bool shader_is_used = false; for (size_t f = 0; f < FaceIndices.length(); ++f) { if (FaceIndices[f] == shader_num) { shader_is_used = true; break; } } if (shader_is_used == false) { //Shader isn't actually used, so continue to the next one. continue; } //out << "Found attached shader: "; //Attach all properties previously associated with this shader to //this NiTriShape MFnDependencyNode fnDep(Shaders[shader_num]); //Find the shader that this shading group connects to MPlug p = fnDep.findPlug("surfaceShader"); MPlugArray plugs; p.connectedTo(plugs, true, false); for (unsigned int i = 0; i < plugs.length(); ++i) { if (plugs[i].node().hasFn(MFn::kLambert)) { fnDep.setObject(plugs[i].node()); break; } } //out << fnDep.name().asChar() << endl; vector<NiPropertyRef> niProps = this->translatorData->shaders[fnDep.name().asChar()]; propGroups.push_back(niProps); } cs.SetPropGroups(propGroups); //out << "Export vertex and normal data" << endl; // attach an iterator to the mesh MItMeshPolygon itPoly(mesh, &stat); if (stat != MS::kSuccess) { throw runtime_error("Failed to create polygon iterator."); } // Create a list of faces with vertex IDs, and duplicate normals so they have the same ID for (; !itPoly.isDone(); itPoly.next()) { int poly_vert_count = itPoly.polygonVertexCount(&stat); if (stat != MS::kSuccess) { throw runtime_error("Failed to get vertex count."); } //Ignore polygons with less than 3 vertices if (poly_vert_count < 3) { continue; } ComplexFace cf; //Assume all faces use material 0 for now cf.propGroupIndex = 0; for (int i = 0; i < poly_vert_count; ++i) { ComplexPoint cp; cp.vertexIndex = itPoly.vertexIndex(i); cp.normalIndex = itPoly.normalIndex(i); if (niColors.size() > 0) { int color_index; stat = meshFn.getFaceVertexColorIndex(itPoly.index(), i, color_index); if (stat != MS::kSuccess) { //out << stat.errorString().asChar() << endl; throw runtime_error("Failed to get vertex color."); } cp.colorIndex = color_index; } //Get the UV set names used by this particular vertex MStringArray vertUvSetNames; itPoly.getUVSetNames(vertUvSetNames); for (unsigned int j = 0; j < vertUvSetNames.length(); ++j) { TexCoordIndex tci; tci.texCoordSetIndex = uvSetNums[vertUvSetNames[j].asChar()]; int uv_index; itPoly.getUVIndex(i, uv_index, &vertUvSetNames[j]); tci.texCoordIndex = uv_index; cp.texCoordIndices.push_back(tci); } cf.points.push_back(cp); } nif_faces.push_back(cf); } //Set shader/face association if (nif_faces.size() != FaceIndices.length()) { throw runtime_error("Num faces found do not match num faces reported."); } for (unsigned int face_index = 0; face_index < nif_faces.size(); ++face_index) { nif_faces[face_index].propGroupIndex = FaceIndices[face_index]; } cs.SetFaces(nif_faces); //--Skin Processing--// //Look up any skin clusters if (this->translatorData->meshClusters.find(visibleMeshFn.fullPathName().asChar()) != this->translatorData->meshClusters.end()) { const vector<MObject> & clusters = this->translatorData->meshClusters[visibleMeshFn.fullPathName().asChar()]; if (clusters.size() > 1) { throw runtime_error("Objects with multiple skin clusters affecting them are not currently supported. Try deleting the history and re-binding them."); } vector<MObject>::const_iterator cluster = clusters.begin(); if (cluster->isNull() != true) { MFnSkinCluster clusterFn(*cluster); //out << "Processing skin..." << endl; //Get path to visible mesh MDagPath meshPath; visibleMeshFn.getPath(meshPath); //out << "Getting a list of all verticies in this mesh" << endl; //Get a list of all vertices in this mesh MFnSingleIndexedComponent compFn; MObject vertices = compFn.create(MFn::kMeshVertComponent); MItGeometry gIt(meshPath); MIntArray vertex_indices(gIt.count()); for (int vert_index = 0; vert_index < gIt.count(); ++vert_index) { vertex_indices[vert_index] = vert_index; } compFn.addElements(vertex_indices); //out << "Getting Influences" << endl; //Get influences MDagPathArray myBones; clusterFn.influenceObjects(myBones, &stat); //out << "Creating a list of NiNodeRefs of influences." << endl; //Create list of NiNodeRefs of influences vector<NiNodeRef> niBones(myBones.length()); for (unsigned int bone_index = 0; bone_index < niBones.size(); ++bone_index) { const char* boneName = myBones[bone_index].fullPathName().asChar(); if (this->translatorData->nodes.find(myBones[bone_index].fullPathName().asChar()) == this->translatorData->nodes.end()) { //There is a problem; one of the joints was not exported. Abort. throw runtime_error("One of the joints necessary to export a bound skin was not exported."); } niBones[bone_index] = this->translatorData->nodes[myBones[bone_index].fullPathName().asChar()]; } //out << "Getting weights from Maya" << endl; //Get weights from Maya MDoubleArray myWeights; unsigned int bone_count = myBones.length(); stat = clusterFn.getWeights(meshPath, vertices, myWeights, bone_count); if (stat != MS::kSuccess) { //out << stat.errorString().asChar() << endl; throw runtime_error("Failed to get vertex weights."); } //out << "Setting skin influence list in ComplexShape" << endl; //Set skin information in ComplexShape cs.SetSkinInfluences(niBones); //out << "Adding weights to ComplexShape vertices" << endl; //out << "Number of weights: " << myWeights.length() << endl; //out << "Number of bones: " << myBones.length() << endl; //out << "Number of Maya vertices: " << gIt.count() << endl; //out << "Number of NIF vertices: " << int(nif_vts.size()) << endl; unsigned int weight_index = 0; SkinInfluence sk; for (unsigned int vert_index = 0; vert_index < nif_vts.size(); ++vert_index) { for (unsigned int bone_index = 0; bone_index < myBones.length(); ++bone_index) { //out << "vert_index: " << vert_index << " bone_index: " << bone_index << " weight_index: " << weight_index << endl; // Only bother with weights that are significant if (myWeights[weight_index] > 0.0f) { sk.influenceIndex = bone_index; sk.weight = float(myWeights[weight_index]); nif_vts[vert_index].weights.push_back(sk); } ++weight_index; } } } MPlugArray connected_dismember_plugs; MObjectArray dismember_nodes; meshFn.findPlug("message").connectedTo(connected_dismember_plugs, false, true); bool has_valid_dismemember_partitions = true; int faces_count = cs.GetFaces().size(); int current_face_index; vector<BodyPartList> body_parts_list; vector<uint> dismember_faces(faces_count, 0); for (int x = 0; x < connected_dismember_plugs.length(); x++) { MFnDependencyNode dependency_node(connected_dismember_plugs[x].node()); if (dependency_node.typeName() == "nifDismemberPartition") { dismember_nodes.append(dependency_node.object()); } } if (dismember_nodes.length() == 0) { has_valid_dismemember_partitions = false; } else { int blind_data_id; int blind_data_value; MStatus status; MPlug target_faces_plug; MItMeshPolygon it_polygons(meshFn.object()); MString mel_command; MStringArray current_body_parts_flags; MFnDependencyNode current_dismember_node; MFnDependencyNode current_blind_data_node; //Naive sort here, there is no reason and is extremely undesirable and not recommended to have more //than 10-20 dismember partitions out of many reasons, so it's okay here //as it makes the code easier to understand vector<int> dismember_nodes_id(dismember_nodes.length(), -1); for (int x = 0; x < dismember_nodes.length(); x++) { current_dismember_node.setObject(dismember_nodes[x]); connected_dismember_plugs.clear(); current_dismember_node.findPlug("targetFaces").connectedTo(connected_dismember_plugs, true, false); if (connected_dismember_plugs.length() == 0) { has_valid_dismemember_partitions = false; break; } current_blind_data_node.setObject(connected_dismember_plugs[0].node()); dismember_nodes_id[x] = current_blind_data_node.findPlug("typeId").asInt(); } for (int x = 0; x < dismember_nodes.length() - 1; x++) { for (int y = x + 1; y < dismember_nodes.length(); y++) { if (dismember_nodes_id[x] > dismember_nodes_id[y]) { MObject aux = dismember_nodes[x]; blind_data_id = dismember_nodes_id[x]; dismember_nodes[x] = dismember_nodes[y]; dismember_nodes_id[x] = dismember_nodes_id[y]; dismember_nodes[y] = aux; dismember_nodes_id[y] = blind_data_id; } } } for (int x = 0; x < dismember_nodes.length(); x++) { current_dismember_node.setObject(dismember_nodes[x]); target_faces_plug = current_dismember_node.findPlug("targetFaces"); connected_dismember_plugs.clear(); target_faces_plug.connectedTo(connected_dismember_plugs, true, false); if (connected_dismember_plugs.length() > 0) { current_blind_data_node.setObject(connected_dismember_plugs[0].node()); current_face_index = 0; blind_data_id = current_blind_data_node.findPlug("typeId").asInt(); for (it_polygons.reset(); !it_polygons.isDone(); it_polygons.next()) { if (it_polygons.polygonVertexCount() >= 3) { status = meshFn.getIntBlindData(it_polygons.index(), MFn::Type::kMeshPolygonComponent, blind_data_id, "dismemberValue", blind_data_value); if (status == MStatus::kSuccess && blind_data_value == 1 && meshFn.hasBlindDataComponentId(it_polygons.index(), MFn::Type::kMeshPolygonComponent, blind_data_id)) { dismember_faces[current_face_index] = x; } current_face_index++; } } } else { has_valid_dismemember_partitions = false; break; } mel_command = "getAttr "; mel_command += current_dismember_node.name(); mel_command += ".bodyPartsFlags"; status = MGlobal::executeCommand(mel_command, current_body_parts_flags); BSDismemberBodyPartType body_part_type = NifDismemberPartition::stringArrayToBodyPartType(current_body_parts_flags); current_body_parts_flags.clear(); mel_command = "getAttr "; mel_command += current_dismember_node.name(); mel_command += ".partsFlags"; status = MGlobal::executeCommand(mel_command, current_body_parts_flags); BSPartFlag part_type = NifDismemberPartition::stringArrayToPart(current_body_parts_flags); current_body_parts_flags.clear(); BodyPartList body_part; body_part.bodyPart = body_part_type; body_part.partFlag = part_type; body_parts_list.push_back(body_part); } } if (has_valid_dismemember_partitions == false) { MGlobal::displayWarning("No proper dismember partitions, generating default ones for " + meshFn.name()); for (int x = 0; x < dismember_faces.size(); x++) { dismember_faces[x] = 0; } BodyPartList body_part; body_part.bodyPart = (BSDismemberBodyPartType)0; body_part.partFlag = (BSPartFlag)(PF_EDITOR_VISIBLE | PF_START_NET_BONESET); body_parts_list.clear(); body_parts_list.push_back(body_part); } cs.SetDismemberPartitionsBodyParts(body_parts_list); cs.SetDismemberPartitionsFaces(dismember_faces); } //out << "Setting vertex info" << endl; //Set vertex info now that any skins have been processed cs.SetVertices(nif_vts); //ComplexShape is now complete, so split it //Get parent NiNodeRef parNode = this->translatorUtils->GetDAGParent(dagNode); Matrix44 transform = Matrix44::IDENTITY; vector<NiNodeRef> influences = cs.GetSkinInfluences(); if (influences.size() > 0) { //This is a skin, so we use the common ancestor of all influences //as the parent vector<NiAVObjectRef> objects; for (size_t i = 0; i < influences.size(); ++i) { objects.push_back(StaticCast<NiAVObject>(influences[i])); } //Get world transform of existing parent Matrix44 oldParWorld = parNode->GetWorldTransform(); //Set new parent node parNode = FindCommonAncestor(objects); transform = oldParWorld * parNode->GetWorldTransform().Inverse(); } //Get transform using temporary NiAVObject NiAVObjectRef tempAV = new NiAVObject; this->nodeExporter->ExportAV(tempAV, dagNode); NiAVObjectRef avObj; if (this->translatorOptions->exportTangentSpace == "falloutskyrimtangentspace") { //out << "Split ComplexShape from " << meshFn.name().asChar() << endl; avObj = cs.Split(parNode, tempAV->GetLocalTransform() * transform, this->translatorOptions->exportBonesPerSkinPartition, this->translatorOptions->exportAsTriStrips, true, this->translatorOptions->exportMinimumVertexWeight, 16); } else { avObj = cs.Split(parNode, tempAV->GetLocalTransform() * transform, this->translatorOptions->exportBonesPerSkinPartition, this->translatorOptions->exportAsTriStrips, false, this->translatorOptions->exportMinimumVertexWeight); } //out << "Get the NiAVObject portion of the root of the split" <<endl; //Get the NiAVObject portion of the root of the split avObj->SetName(tempAV->GetName()); avObj->SetVisibility(tempAV->GetVisibility()); avObj->SetFlags(tempAV->GetFlags()); //If polygon mesh is hidden, hide tri_shape MPlug vis = visibleMeshFn.findPlug(MString("visibility")); bool visibility; vis.getValue(visibility); NiNodeRef splitRoot = DynamicCast<NiNode>(avObj); if (splitRoot != NULL) { //Root is a NiNode with NiTriBasedGeom children. vector<NiAVObjectRef> children = splitRoot->GetChildren(); for (unsigned c = 0; c < children.size(); ++c) { //Set the default collision propogation flag to "use triangles" children[c]->SetFlags(2); // Make the mesh invisible if necessary if (visibility == false) { children[c]->SetVisibility(false); } } } else { //Root must be a NiTriBasedGeom. Make it invisible if necessary if (visibility == false) { avObj->SetVisibility(false); } } }
MStatus MayaToFuji::doIt( const MArgList& args) { MStatus stat = MStatus::kSuccess; MGlobal::displayInfo("Executing mayatoFuji..."); logger.setLogLevel(Logging::Debug); MArgDatabase argData(syntax(), args); int width = -1; int height = -1; if ( argData.isFlagSet("-width", &stat)) { argData.getFlagArgument("-width", 0, width); logger.debug(MString("width: ") + width); } if ( argData.isFlagSet("-height", &stat)) { argData.getFlagArgument("-height", 0, height); logger.debug(MString("height: ") + height); } if ( argData.isFlagSet("-stopIpr", &stat)) { logger.debug(MString("-stopIpr")); EventQueue::Event e; e.type = EventQueue::Event::IPRSTOP; theRenderEventQueue()->push(e); return MS::kSuccess; } if ( argData.isFlagSet("-pauseIpr", &stat)) { logger.debug(MString("-pauseIpr")); return MS::kSuccess; } MayaScene::RenderType rtype = MayaScene::NORMAL; if ( argData.isFlagSet("-startIpr", &stat)) { logger.debug(MString("-startIpr")); rtype = MayaScene::IPR; } else { logger.debug(MString("normal render")); } // if we are here, we want a normal or an startIPR rendering, so initialize the scene mtfu_MayaScene *mayaScene = new mtfu_MayaScene(rtype); if( !mayaScene->good ) { logger.error("Problems have occurred during creation of mayaScene(). Sorry cannot proceed.\n\n"); return MS::kFailure; } if( !mayaScene->parseScene(MayaScene::HIERARCHYPARSE) ) { logger.error("Problems have occurred during parsing of the scene. Sorry cannot proceed.\n\n"); return MS::kFailure; } if ( argData.isFlagSet("-camera", &stat)) { MDagPath camera; MSelectionList selectionList; argData.getFlagArgument("-camera", 0, selectionList); stat = selectionList.getDagPath(0, camera); camera.extendToShape(); logger.debug(MString("camera: ") + camera.fullPathName()); mayaScene->setCurrentCamera(camera); } if( height > 0) mayaScene->renderGlobals->imgHeight = height; if( width > 0) mayaScene->renderGlobals->imgWidth = width; if(!mayaScene->renderScene()) { logger.error("Problems have occurred during rendering of the scene. Sorry cannot proceed.\n\n"); return MS::kFailure; } MGlobal::displayInfo("mayatoFuji rendering done.\n"); return MStatus::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 = *mJobCtx.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 = mJobCtx.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(mJobCtx.mStage, editTarget); // == Activate/Deactivate UsdPrims UsdPrimRange rng = UsdPrimRange::AllPrims(mJobCtx.mStage->GetPseudoRoot()); std::vector<UsdPrim> primsToDeactivate; for (auto it = rng.begin(); it != rng.end(); ++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; }
bool HesperisIO::CreateMeshGroup(MDagPathArray & paths, ATriangleMeshGroup * dst) { MStatus stat; const unsigned n = paths.length(); unsigned i, j; int numPnts = 0; unsigned numNodes = 0; unsigned numTris = 0; MGlobal::displayInfo(" hesperis check meshes"); MIntArray triangleCounts, triangleVertices; MPointArray ps; MPoint wp; MMatrix worldTm; for(i=0; i< n; i++) { MFnMesh fmesh(paths[i].node(), &stat); if(!stat) continue; numNodes++; numPnts += fmesh.numVertices(); fmesh.getTriangles(triangleCounts, triangleVertices); numTris += triangleVertices.length() / 3; } if(numNodes < 1 || numTris < 1) { MGlobal::displayInfo(" insufficient mesh data"); return false; } MGlobal::displayInfo(MString(" mesh count: ") + numNodes + MString(" vertex count: ") + numPnts + MString(" triangle count: ") + numTris); dst->create(numPnts, numTris, numNodes); Vector3F * pnts = dst->points(); unsigned * inds = dst->indices(); unsigned * pntDrift = dst->pointDrifts(); unsigned * indDrift = dst->indexDrifts(); unsigned pDrift = 0; unsigned iDrift = 0; unsigned iNode = 0; for(i=0; i< n; i++) { MFnMesh fmesh(paths[i].node(), &stat); if(!stat) continue; //MGlobal::displayInfo(MString("p drift ")+pDrift+ // MString("i drift ")+iDrift); worldTm = GetWorldTransform(paths[i]); fmesh.getPoints(ps, MSpace::kObject); fmesh.getTriangles(triangleCounts, triangleVertices); for(j=0; j<fmesh.numVertices(); j++) { wp = ps[j] * worldTm; pnts[pDrift + j].set((float)wp.x, (float)wp.y, (float)wp.z); } for(j=0; j<triangleVertices.length(); j++) inds[iDrift + j] = pDrift + triangleVertices[j]; pntDrift[iNode] = pDrift; indDrift[iNode] = iDrift; pDrift += fmesh.numVertices(); iDrift += triangleVertices.length(); iNode++; } return true; }
bool usdWriteJob::beginJob(const std::string &iFileName, bool append, double startTime, double endTime) { // Check for DAG nodes that are a child of an already specified DAG node to export // if that's the case, report the issue and skip the export PxrUsdMayaUtil::ShapeSet::const_iterator m, n; PxrUsdMayaUtil::ShapeSet::const_iterator endPath = mJobCtx.mArgs.dagPaths.end(); for (m = mJobCtx.mArgs.dagPaths.begin(); m != endPath; ) { MDagPath path1 = *m; m++; for (n = m; n != endPath; n++) { MDagPath path2 = *n; if (PxrUsdMayaUtil::isAncestorDescendentRelationship(path1,path2)) { MString errorMsg = path1.fullPathName(); errorMsg += " and "; errorMsg += path2.fullPathName(); errorMsg += " have an ancestor relationship. Skipping USD Export."; MGlobal::displayError(errorMsg); return false; } } // for n } // for m // Make sure the file name is a valid one with a proper USD extension. const std::string iFileExtension = TfStringGetSuffix(iFileName, '.'); if (SdfLayer::IsAnonymousLayerIdentifier(iFileName) || iFileExtension == PxrUsdMayaTranslatorTokens->UsdFileExtensionDefault || iFileExtension == PxrUsdMayaTranslatorTokens->UsdFileExtensionASCII || iFileExtension == PxrUsdMayaTranslatorTokens->UsdFileExtensionCrate) { mFileName = iFileName; } else { mFileName = TfStringPrintf("%s.%s", iFileName.c_str(), PxrUsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText()); } MGlobal::displayInfo("usdWriteJob::beginJob: Create stage file "+MString(mFileName.c_str())); if (!mJobCtx.openFile(mFileName, append)) { return false; } // Set time range for the USD file mJobCtx.mStage->SetStartTimeCode(startTime); mJobCtx.mStage->SetEndTimeCode(endTime); mModelKindWriter.Reset(); // Setup the requested render layer mode: // defaultLayer - Switch to the default render layer before exporting, // then switch back afterwards (no layer switching if // the current layer IS the default layer). // currentLayer - No layer switching before or after exporting. Just // use whatever is the current render layer for export. // modelingVariant - Switch to the default render layer before exporting, // and export each render layer in the scene as a // modeling variant, then switch back afterwards (no // layer switching if the current layer IS the default // layer). The default layer will be made the default // modeling variant. MFnRenderLayer currentLayer(MFnRenderLayer::currentLayer()); mCurrentRenderLayerName = currentLayer.name(); if (mJobCtx.mArgs.renderLayerMode == PxUsdExportJobArgsTokens->modelingVariant) { // Handle usdModelRootOverridePath for USD Variants MFnRenderLayer::listAllRenderLayers(mRenderLayerObjs); if (mRenderLayerObjs.length() > 1) { mJobCtx.mArgs.usdModelRootOverridePath = SdfPath("/_BaseModel_"); } } // Switch to the default render layer unless the renderLayerMode is // 'currentLayer', or the default layer is already the current layer. if (mJobCtx.mArgs.renderLayerMode != PxUsdExportJobArgsTokens->currentLayer && MFnRenderLayer::currentLayer() != MFnRenderLayer::defaultRenderLayer()) { // Set the RenderLayer to the default render layer MFnRenderLayer defaultLayer(MFnRenderLayer::defaultRenderLayer()); MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+ defaultLayer.name(), false, false); } // Pre-process the argument dagPath path names into two sets. One set // contains just the arg dagPaths, and the other contains all parents of // arg dagPaths all the way up to the world root. Partial path names are // enough because Maya guarantees them to still be unique, and they require // less work to hash and compare than full path names. TfHashSet<std::string, TfHash> argDagPaths; TfHashSet<std::string, TfHash> argDagPathParents; PxrUsdMayaUtil::ShapeSet::const_iterator end = mJobCtx.mArgs.dagPaths.end(); for (PxrUsdMayaUtil::ShapeSet::const_iterator it = mJobCtx.mArgs.dagPaths.begin(); it != end; ++it) { MDagPath curDagPath = *it; std::string curDagPathStr(curDagPath.partialPathName().asChar()); argDagPaths.insert(curDagPathStr); while (curDagPath.pop() && curDagPath.length() >= 0) { curDagPathStr = curDagPath.partialPathName().asChar(); if (argDagPathParents.find(curDagPathStr) != argDagPathParents.end()) { // We've already traversed up from this path. break; } argDagPathParents.insert(curDagPathStr); } } // Now do a depth-first traversal of the Maya DAG from the world root. // We keep a reference to arg dagPaths as we encounter them. MDagPath curLeafDagPath; for (MItDag itDag(MItDag::kDepthFirst, MFn::kInvalid); !itDag.isDone(); itDag.next()) { MDagPath curDagPath; itDag.getPath(curDagPath); std::string curDagPathStr(curDagPath.partialPathName().asChar()); if (argDagPathParents.find(curDagPathStr) != argDagPathParents.end()) { // This dagPath is a parent of one of the arg dagPaths. It should // be included in the export, but not necessarily all of its // children should be, so we continue to traverse down. } else if (argDagPaths.find(curDagPathStr) != argDagPaths.end()) { // This dagPath IS one of the arg dagPaths. It AND all of its // children should be included in the export. curLeafDagPath = curDagPath; } else if (!MFnDagNode(curDagPath).hasParent(curLeafDagPath.node())) { // This dagPath is not a child of one of the arg dagPaths, so prune // it and everything below it from the traversal. itDag.prune(); continue; } if (!needToTraverse(curDagPath) && curDagPath.length() > 0) { // This dagPath and all of its children should be pruned. itDag.prune(); } else { MayaPrimWriterPtr primWriter = mJobCtx.createPrimWriter(curDagPath); if (primWriter) { mJobCtx.mMayaPrimWriterList.push_back(primWriter); // Write out data (non-animated/default values). if (const auto& usdPrim = primWriter->getPrim()) { primWriter->write(UsdTimeCode::Default()); MDagPath dag = primWriter->getDagPath(); mDagPathToUsdPathMap[dag] = usdPrim.GetPath(); // If we are merging transforms and the object derives from // MayaTransformWriter but isn't actually a transform node, we // need to add its parent. if (mJobCtx.mArgs.mergeTransformAndShape) { MayaTransformWriterPtr xformWriter = std::dynamic_pointer_cast<MayaTransformWriter>(primWriter); if (xformWriter) { MDagPath xformDag = xformWriter->getTransformDagPath(); mDagPathToUsdPathMap[xformDag] = usdPrim.GetPath(); } } mModelKindWriter.OnWritePrim(usdPrim, primWriter); } if (primWriter->shouldPruneChildren()) { itDag.prune(); } } } } // Writing Materials/Shading PxrUsdMayaTranslatorMaterial::ExportShadingEngines( mJobCtx.mStage, mJobCtx.mArgs.dagPaths, mJobCtx.mArgs.shadingMode, mJobCtx.mArgs.mergeTransformAndShape, mJobCtx.mArgs.usdModelRootOverridePath); if (!mModelKindWriter.MakeModelHierarchy(mJobCtx.mStage)) { return false; } // now we populate the chasers and run export default mChasers.clear(); PxrUsdMayaChaserRegistry::FactoryContext ctx(mJobCtx.mStage, mDagPathToUsdPathMap, mJobCtx.mArgs); for (const std::string& chaserName : mJobCtx.mArgs.chaserNames) { if (PxrUsdMayaChaserRefPtr fn = PxrUsdMayaChaserRegistry::GetInstance().Create(chaserName, ctx)) { mChasers.push_back(fn); } else { std::string error = TfStringPrintf("Failed to create chaser: %s", chaserName.c_str()); MGlobal::displayError(MString(error.c_str())); } } for (const PxrUsdMayaChaserRefPtr& chaser : mChasers) { if (!chaser->ExportDefault()) { return false; } } return true; }
MStatus lrutils::loadGeoReference(MString geoFilePath, MString geoName, MString & name, MObject & geoObj) { MStatus status = MS::kFailure; MString projPath = MGlobal::executeCommandStringResult(MString("workspace -q -rd;"),false,false); MString relativePath = geoFilePath.substring(2,geoFilePath.numChars() - 1); //assemble the full file path of the geometry file MString fullGeoPath = projPath + relativePath; //load the geometry file as a reference into the current scene //check to see if the referenced file has already been used MStringArray refNodeList; status = MFileIO::getReferences(refNodeList, true); MyCheckStatus(status, "getReferences failed"); int numReferences = 0; for(unsigned int i = 0; i < refNodeList.length(); i++) { MString tmp = refNodeList[i]; string tmp1 = tmp.asChar(); string tmp2 = fullGeoPath.asChar(); if(std::string::npos != tmp1.find(tmp2)) numReferences++; } string str (geoFilePath.asChar()); string key ("/"); size_t found = str.rfind(key); string fileName = str.substr(found+1,str.length()-found-4); string fileNamespace; if(numReferences > 0) { stringstream tmp; tmp << fileName << (numReferences+1); fileNamespace = tmp.str(); } else { fileNamespace = fileName; } { stringstream tmp; tmp << "file -r -type \"mayaAscii\" -gl -loadReferenceDepth \"all\" -namespace \"" << fileNamespace.c_str() << "\" -options \"v=0\" \"" << fullGeoPath.asChar() << "\";"; MString referenceCommand = MString(tmp.str().c_str()); MGlobal::executeCommand(referenceCommand); } //get the referenced geometry transform node and add the metaParent //attribute to it MSelectionList selection; if(numReferences > 0) { name += (boost::lexical_cast<string>(numReferences+1)).c_str(); } stringstream geoRefName; geoRefName << fileNamespace << ":" << geoName; MString mGeoRefName = MString(geoRefName.str().c_str()); status = selection.add( mGeoRefName, true ); MyCheckStatusReturn(status, "add geoRefName "+mGeoRefName+" to selection failed."); if(selection.length() ) selection.getDependNode(0, geoObj); MFnTransform transformFn; transformFn.setObject(geoObj); MFnMessageAttribute mAttr; MObject transformAttr = mAttr.create("metaParent", "metaParent"); transformFn.addAttribute(transformAttr); if( !geoObj.isNull() ) status = MS::kSuccess; return status; }
MStatus liqSurfaceNode::initialize() { MFnTypedAttribute tAttr; MFnStringData tDefault; MFnNumericAttribute nAttr; MFnEnumAttribute eAttr; MFnLightDataAttribute lAttr; MStatus status; // Create input attributes aRmanShader = tAttr.create( MString("rmanShader"), MString("rms"), MFnData::kString, aRmanShader, &status ); MAKE_INPUT(tAttr); aRmanShaderType = tAttr.create( MString("rmanShaderType"), MString("rst"), MFnData::kString, aRmanShaderType, &status ); MAKE_INPUT(tAttr); aRmanShaderLong = tAttr.create( MString("rmanShaderLong"), MString("rml"), MFnData::kString, aRmanShaderLong, &status ); MAKE_INPUT(tAttr); aRmanShaderLif = tAttr.create( MString("rmanShaderLif"), MString("lif"), MFnData::kString, aRmanShaderLif, &status ); MAKE_INPUT(tAttr); aRmanParams = tAttr.create( MString("rmanParams"), MString("rpr"), MFnData::kStringArray, aRmanParams, &status ); MAKE_INPUT(tAttr); aRmanDetails = tAttr.create( MString("rmanDetails"), MString("rdt"), MFnData::kStringArray, aRmanDetails, &status ); MAKE_INPUT(tAttr); aRmanTypes = tAttr.create( MString("rmanTypes"), MString("rty"), MFnData::kStringArray, aRmanTypes, &status ); MAKE_INPUT(tAttr); aRmanDefaults = tAttr.create( MString("rmanDefaults"), MString("rdf"), MFnData::kStringArray, aRmanDefaults, &status ); MAKE_INPUT(tAttr); aRmanArraySizes = tAttr.create( MString("rmanArraySizes"), MString("ras"), MFnData::kIntArray, aRmanArraySizes, &status ); MAKE_INPUT(tAttr); aRmanLifCmds = tAttr.create( MString("rmanLifCmds"), MString("rlc"), MFnData::kStringArray, aRmanLifCmds, &status ); MAKE_INPUT(tAttr); aRmanMethods = tAttr.create( MString("rmanMethods"), MString("rmt"), MFnData::kStringArray, aRmanMethods, &status ); MAKE_INPUT(tAttr); aRmanIsOutput = tAttr.create( MString("rmanIsOutput"), MString("rio"), MFnData::kIntArray, aRmanIsOutput, &status ); MAKE_INPUT(tAttr); aRmanAccept = tAttr.create( MString("rmanAccept"), MString("rma"), MFnData::kStringArray, aRmanAccept, &status ); MAKE_INPUT(tAttr); aPreviewPrimitive = eAttr.create( "previewPrimitive", "pvp", 7, &status ); eAttr.addField( "Sphere", 0 ); eAttr.addField( "Cube", 1 ); eAttr.addField( "Cylinder", 2 ); eAttr.addField( "Torus", 3 ); eAttr.addField( "Plane", 4 ); eAttr.addField( "Teapot", 5 ); eAttr.addField( "Custom", 6 ); eAttr.addField( "(globals)",7 ); MAKE_NONKEYABLE_INPUT(eAttr); CHECK_MSTATUS(eAttr.setConnectable(false ) ); aPreviewCustomPrimitive = tAttr.create( MString("previewCustomPrimitive"), MString("pcp"), MFnData::kString, aPreviewCustomPrimitive, &status ); MAKE_INPUT(tAttr); aPreviewCustomBackplane = tAttr.create( MString("previewCustomBackplane"), MString("pcb"), MFnData::kString, aPreviewCustomBackplane, &status ); MAKE_INPUT(tAttr); aPreviewCustomLightRig = tAttr.create( MString("previewCustomLights"), MString("pcl"), MFnData::kString, aPreviewCustomLightRig, &status ); MAKE_INPUT(tAttr); aPreviewObjectSize = nAttr.create("previewObjectSize", "pos", MFnNumericData::kDouble, 1.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setConnectable(false ) ); aPreviewShadingRate = nAttr.create("previewShadingRate", "psr", MFnNumericData::kDouble, 1.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setConnectable(false ) ); aPreviewBackplane = nAttr.create("previewBackplane", "pbp", MFnNumericData::kBoolean, true, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setConnectable(false ) ); aPreviewIntensity = nAttr.create("previewIntensity", "pi", MFnNumericData::kDouble, 1.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setConnectable(false ) ); aGLPreviewTexture = nAttr.createColor("GLPreviewTexture", "gpt"); nAttr.setDefault( -1.0, -1.0, -1.0 ); nAttr.setDisconnectBehavior( MFnAttribute::kReset ); MAKE_INPUT(nAttr); aColor = nAttr.createColor("color", "cs"); nAttr.setDefault( 1.0, 1.0, 1.0 ); nAttr.setDisconnectBehavior( MFnAttribute::kReset ); MAKE_INPUT(nAttr); aOpacity = nAttr.createColor("opacity", "os"); nAttr.setDefault( 1.0, 1.0, 1.0 ); MAKE_INPUT(nAttr); aTransparency = nAttr.createColor("transparency", "ts"); // Needed by Maya for Open Gl preview in "5" mode, invert opacity in compute nAttr.setDefault( 0.0, 0.0, 0.0 ); MAKE_INPUT(nAttr); aShaderSpace = tAttr.create( MString("shaderSpace"), MString("ssp"), MFnData::kString, aShaderSpace, &status ); MAKE_INPUT(tAttr); aDisplacementBound = nAttr.create("displacementBound", "db", MFnNumericData::kDouble, 0.0, &status); MAKE_INPUT(nAttr); MObject defaultSpaceObj = tDefault.create( MString("shader"), &status); aDisplacementBoundSpace = tAttr.create( MString("displacementBoundSpace"), MString("dbs"), MFnData::kString, defaultSpaceObj, &status ); MAKE_INPUT(tAttr); aOutputInShadow = nAttr.create("outputInShadow", "ois", MFnNumericData::kBoolean, 0.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); aVisiblePoints = nAttr.create( "useVisiblePoints", "uvp", MFnNumericData::kBoolean, false, &status ); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS( nAttr.setConnectable(false ) ); // resolution attribute for maya's hardware renderer aResolution = nAttr.create("resolution", "res", MFnNumericData::kInt, 32, &status); CHECK_MSTATUS(nAttr.setStorable( true ) ); CHECK_MSTATUS(nAttr.setReadable( true ) ); CHECK_MSTATUS(nAttr.setWritable( true ) ); CHECK_MSTATUS(nAttr.setHidden( true ) ); // refreshPreview must be true to allow refresh aRefreshPreview = nAttr.create("refreshPreview", "rfp", MFnNumericData::kBoolean, 0.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setHidden(true ) ); // dynamic shader attr //aCi = nAttr.createColor("Ci", "ci"); //nAttr.setDefault( 1.0, 1.0, 1.0 ); //MAKE_INPUT(nAttr); //aOi = nAttr.createColor("Oi", "oi"); //nAttr.setDefault( 1.0, 1.0, 1.0 ); //MAKE_INPUT(nAttr); // create attributes for maya renderer // lambertian control aMayaIgnoreLights = nAttr.create("mayaIgnoreLights", "mil", MFnNumericData::kBoolean, 0.0, &status); MAKE_INPUT(nAttr); aMayaKa = nAttr.create("mayaKa", "mka", MFnNumericData::kFloat, 0.2, &status); MAKE_INPUT(nAttr); aMayaKd = nAttr.create("mayaKd", "mkd", MFnNumericData::kFloat, 0.8, &status); MAKE_INPUT(nAttr); // Camera Normals aNormalCameraX = nAttr.create( "normalCameraX", "nx", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aNormalCameraY = nAttr.create( "normalCameraY", "ny", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aNormalCameraZ = nAttr.create( "normalCameraZ", "nz", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aNormalCamera = nAttr.create( "normalCamera","n", aNormalCameraX, aNormalCameraY, aNormalCameraZ, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f, 1.0f, 1.0f ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); // Light Direction aLightDirectionX = nAttr.create( "lightDirectionX", "ldx", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aLightDirectionY = nAttr.create( "lightDirectionY", "ldy", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aLightDirectionZ = nAttr.create( "lightDirectionZ", "ldz", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aLightDirection = nAttr.create( "lightDirection", "ld", aLightDirectionX, aLightDirectionY, aLightDirectionZ, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f, 1.0f, 1.0f ) ); // Light Intensity aLightIntensityR = nAttr.create( "lightIntensityR", "lir", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aLightIntensityG = nAttr.create( "lightIntensityG", "lig", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aLightIntensityB = nAttr.create( "lightIntensityB", "lib", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aLightIntensity = nAttr.create( "lightIntensity", "li", aLightIntensityR, aLightIntensityG, aLightIntensityB, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f, 1.0f, 1.0f ) ); // Light aLightAmbient = nAttr.create( "lightAmbient", "la", MFnNumericData::kBoolean, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( true ) ); aLightDiffuse = nAttr.create( "lightDiffuse", "ldf", MFnNumericData::kBoolean, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( true ) ); aLightSpecular = nAttr.create( "lightSpecular", "ls", MFnNumericData::kBoolean, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( false ) ); aLightShadowFraction = nAttr.create( "lightShadowFraction", "lsf", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setReadable( true ) ); CHECK_MSTATUS( nAttr.setWritable( true ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); aPreShadowIntensity = nAttr.create( "preShadowIntensity", "psi", MFnNumericData::kFloat, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); #if MAYA_API_VERSION >= 800 aLightBlindData = nAttr.createAddr( "lightBlindData", "lbld", 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( (void*) 0 ) ); #else aLightBlindData = nAttr.create( "lightBlindData", "lbld", MFnNumericData::kLong, 0, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( false ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( false ) ); CHECK_MSTATUS( nAttr.setDefault( 0 ) ); #endif aLightData = lAttr.create( "lightDataArray", "ltd", aLightDirection, aLightIntensity, aLightAmbient, aLightDiffuse, aLightSpecular, aLightShadowFraction, aPreShadowIntensity, aLightBlindData, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( lAttr.setArray( true ) ); CHECK_MSTATUS( lAttr.setStorable( false ) ); CHECK_MSTATUS( lAttr.setHidden( true ) ); CHECK_MSTATUS( lAttr.setDefault( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, true, true, false, 1.0f, 1.0f, 0 ) ); aEvaluateAtEveryFrame = nAttr.create("evaluateAtEveryFrame", "def", MFnNumericData::kBoolean, 0.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); aPreviewGamma = nAttr.create( "previewGamma", "pg", MFnNumericData::kFloat, 1, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( true ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( true ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); // Create output attributes aOutColor = nAttr.createColor("outColor", "oc"); MAKE_OUTPUT(nAttr); aOutTransparency = nAttr.createColor("outTransparency", "ot"); MAKE_OUTPUT(nAttr); CHECK_MSTATUS( addAttribute( aRmanShader ) ); CHECK_MSTATUS( addAttribute( aRmanShaderType ) ); CHECK_MSTATUS( addAttribute( aRmanShaderLong ) ); CHECK_MSTATUS( addAttribute( aRmanShaderLif ) ); CHECK_MSTATUS( addAttribute( aRmanParams ) ); CHECK_MSTATUS( addAttribute( aRmanDetails ) ); CHECK_MSTATUS( addAttribute( aRmanTypes ) ); CHECK_MSTATUS( addAttribute( aRmanDefaults ) ); CHECK_MSTATUS( addAttribute( aRmanArraySizes ) ); CHECK_MSTATUS( addAttribute( aRmanLifCmds ) ); CHECK_MSTATUS( addAttribute(aRmanMethods) ); CHECK_MSTATUS( addAttribute(aRmanIsOutput) ); CHECK_MSTATUS( addAttribute( aRmanAccept) ); CHECK_MSTATUS( addAttribute( aPreviewPrimitive ) ); CHECK_MSTATUS( addAttribute( aPreviewCustomPrimitive ) ); CHECK_MSTATUS( addAttribute( aPreviewCustomBackplane ) ); CHECK_MSTATUS( addAttribute( aPreviewCustomLightRig ) ); CHECK_MSTATUS( addAttribute( aPreviewObjectSize ) ); CHECK_MSTATUS( addAttribute( aPreviewShadingRate ) ); CHECK_MSTATUS( addAttribute( aPreviewBackplane ) ); CHECK_MSTATUS( addAttribute( aPreviewIntensity ) ); CHECK_MSTATUS( addAttribute(aGLPreviewTexture)); //CHECK_MSTATUS( addAttribute( aCi ) ); //CHECK_MSTATUS( addAttribute( aOi ) ); CHECK_MSTATUS( addAttribute( aColor ) ); CHECK_MSTATUS( addAttribute( aTransparency ) ); CHECK_MSTATUS( addAttribute( aOpacity ) ); CHECK_MSTATUS( addAttribute( aShaderSpace ) ); CHECK_MSTATUS( addAttribute( aDisplacementBound ) ); CHECK_MSTATUS( addAttribute( aDisplacementBoundSpace ) ); CHECK_MSTATUS( addAttribute( aOutputInShadow ) ); CHECK_MSTATUS( addAttribute( aVisiblePoints ) ); CHECK_MSTATUS( addAttribute( aResolution ) ); CHECK_MSTATUS( addAttribute( aRefreshPreview ) ); CHECK_MSTATUS( addAttribute( aMayaIgnoreLights ) ); CHECK_MSTATUS( addAttribute( aMayaKa ) ); CHECK_MSTATUS( addAttribute( aMayaKd ) ); CHECK_MSTATUS( addAttribute( aNormalCamera ) ); CHECK_MSTATUS( addAttribute( aLightData ) ); CHECK_MSTATUS( addAttribute( aEvaluateAtEveryFrame ) ); CHECK_MSTATUS( addAttribute( aPreviewGamma ) ); CHECK_MSTATUS( addAttribute( aOutColor ) ); CHECK_MSTATUS( addAttribute( aOutTransparency ) ); CHECK_MSTATUS(attributeAffects( aGLPreviewTexture, aOutColor )); CHECK_MSTATUS(attributeAffects( aColor, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aOpacity, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aMayaIgnoreLights, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aMayaKa, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aMayaKd, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightIntensityR, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightIntensityB, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightIntensityG, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightIntensity, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aNormalCameraX, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aNormalCameraY, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aNormalCameraZ, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aNormalCamera, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightDirectionX, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightDirectionY, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightDirectionZ, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightDirection, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightAmbient, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightSpecular, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightDiffuse, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightShadowFraction, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aPreShadowIntensity, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightBlindData, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aLightData, aOutColor ) ); CHECK_MSTATUS(attributeAffects( aOpacity, aOutTransparency ) ); return MS::kSuccess; }
CONDITION MLStorage::handleCStoreDataSet(DUL_PRESENTATIONCONTEXT* ctx, MSG_C_STORE_REQ** message, MSG_C_STORE_RESP* response, DUL_ASSOCIATESERVICEPARAMETERS* params, MString& fileName) { MLogClient logClient; logClient.log(MLogClient::MLOG_VERBOSE, params->callingAPTitle, "MLStorage::handleCStoreDataSet", __LINE__, "About to translate and store SOP Instance"); logClient.log(MLogClient::MLOG_VERBOSE, params->callingAPTitle, "MLStorage::handleCStoreDataSet", __LINE__, "File is: " + fileName); MDICOMDomainXlate xlate; MString newDirectory; MString newFile; MPatient patient; MStudy study; MSeries series; MSOPInstance sopInstance; MFileOperations fileOp; { MDICOMWrapper w(fileName); MString s; xlate.translateDICOM(w, patient); xlate.translateDICOM(w, study); s = study.studyInstanceUID(); if (this->checkUID(s) != 0) { logClient.logTimeStamp(MLogClient::MLOG_ERROR, MString("Detected illegal Study Instance UID: ") + s); logClient.logTimeStamp(MLogClient::MLOG_ERROR, "Will return an error in the C-Store response"); response->status = MSG_K_C_STORE_OUTOFRESOURCES; response->conditionalFields |= MSG_K_C_STORERESP_ERRORCOMMENT; ::strcpy(response->errorComment , "Illegal Study Instance UID in composite object"); goto exit_handleCStoreDataSet; } xlate.translateDICOM(w, series); s = series.seriesInstanceUID(); if (this->checkUID(s) != 0) { logClient.logTimeStamp(MLogClient::MLOG_ERROR, MString("Detected illegal Series Instance UID: ") + s); logClient.logTimeStamp(MLogClient::MLOG_ERROR, "Will return an error in the C-Store response"); response->status = MSG_K_C_STORE_OUTOFRESOURCES; response->conditionalFields |= MSG_K_C_STORERESP_ERRORCOMMENT; ::strcpy(response->errorComment , "Illegal Series Instance UID in composite object"); goto exit_handleCStoreDataSet; } xlate.translateDICOM(w, sopInstance); s = sopInstance.instanceUID(); if (this->checkUID(s) != 0) { logClient.logTimeStamp(MLogClient::MLOG_ERROR, MString("Detected illegal SOP Instance UID: ") + s); logClient.logTimeStamp(MLogClient::MLOG_ERROR, "Will return an error in the C-Store response"); response->status = MSG_K_C_STORE_OUTOFRESOURCES; response->conditionalFields |= MSG_K_C_STORERESP_ERRORCOMMENT; ::strcpy(response->errorComment , "Illegal SOP Instance UID in composite object"); goto exit_handleCStoreDataSet; } MString sopInstanceUID = sopInstance.instanceUID(); logClient.log(MLogClient::MLOG_VERBOSE, params->callingAPTitle, "MLStorage::handleCStoreDataSet", __LINE__, "SOP Instance UID: " + sopInstanceUID); MString slash("/"); MString callingAPTitle(params->callingAPTitle); char x[65]; sopInstance.instanceUID().safeExport(x, sizeof(x)); if (x[0] == 'x') { // Special case newDirectory = mStorageDir + slash + params->callingAPTitle + slash + study.studyInstanceUID(); } else { newDirectory = mStorageDir + slash + params->callingAPTitle + slash + study.studyInstanceUID() + slash + series.seriesInstanceUID(); } newFile = newDirectory + slash + sopInstance.instanceUID(); sopInstance.fileName(newFile); } fileOp.createDirectory(newDirectory); fileOp.unlink(newFile); fileOp.rename(fileName, newFile); logClient.log(MLogClient::MLOG_VERBOSE, params->callingAPTitle, "MLStorage::handleCStoreDataSet", __LINE__, "File Rename: " + newFile); if (sopInstance.instanceUID() != "x") mImageManager->enterSOPInstance(patient, study, series, sopInstance); logClient.log(MLogClient::MLOG_VERBOSE, params->callingAPTitle, "MLStorage::handleCStoreDataSet", __LINE__, "C-Store Data Set complete"); exit_handleCStoreDataSet: return 0; }
// creator // void* viewCallbackTest::creator() { return (void *) (new viewCallbackTest); } // newSyntax // // Buffer operation = -bo/-bufferOperation <string> = (invert | showDepth) const char *bufferOperationShortName = "-bo"; const char *bufferOperationLongName = "-bufferOperation"; #define _NUMBER_BUFFER_OPERATIONS_ 2 const MString bufferOperationStrings[_NUMBER_BUFFER_OPERATIONS_ ] = { MString("invert"), MString("showDepth") }; const MbufferOperation bufferOperations[_NUMBER_BUFFER_OPERATIONS_] = { kInvertColorBuffer, kDrawDepthBuffer }; MSyntax viewCallbackTest::newSyntax() { MSyntax syntax; syntax.addFlag(bufferOperationShortName, bufferOperationLongName, MSyntax::kString); // Name of model panel to monitor // syntax.addArg(MSyntax::kString); return syntax; }
MStatus liqCoShaderNode::initialize() { MFnTypedAttribute tAttr; MFnNumericAttribute nAttr; MFnEnumAttribute eAttr; MStatus status; // Create input attributes aRmanShader = tAttr.create( MString("rmanShader"), MString("rms"), MFnData::kString, aRmanShader, &status ); MAKE_INPUT(tAttr); aRmanShaderType = tAttr.create( MString("rmanShaderType"), MString("rst"), MFnData::kString, aRmanShaderType, &status ); MAKE_INPUT(tAttr); aRmanShaderLong = tAttr.create( MString("rmanShaderLong"), MString("rml"), MFnData::kString, aRmanShaderLong, &status ); MAKE_INPUT(tAttr); aRmanShaderLif = tAttr.create( MString("rmanShaderLif"), MString("lif"), MFnData::kString, aRmanShaderLif, &status ); MAKE_INPUT(tAttr); aRmanParams = tAttr.create( MString("rmanParams"), MString("rpr"), MFnData::kStringArray, aRmanParams, &status ); MAKE_INPUT(tAttr); aRmanDetails = tAttr.create( MString("rmanDetails"), MString("rdt"), MFnData::kStringArray, aRmanDetails, &status ); MAKE_INPUT(tAttr); aRmanTypes = tAttr.create( MString("rmanTypes"), MString("rty"), MFnData::kStringArray, aRmanTypes, &status ); MAKE_INPUT(tAttr); aRmanDefaults = tAttr.create( MString("rmanDefaults"), MString("rdf"), MFnData::kStringArray, aRmanDefaults, &status ); MAKE_INPUT(tAttr); aRmanArraySizes = tAttr.create( MString("rmanArraySizes"), MString("ras"), MFnData::kIntArray, aRmanArraySizes, &status ); MAKE_INPUT(tAttr); aRmanLifCmds = tAttr.create( MString("rmanLifCmds"), MString("rlc"), MFnData::kStringArray, aRmanLifCmds, &status ); MAKE_INPUT(tAttr); aRmanMethods = tAttr.create( MString("rmanMethods"), MString("rmt"), MFnData::kStringArray, aRmanMethods, &status ); MAKE_INPUT(tAttr); aRmanIsOutput = tAttr.create( MString("rmanIsOutput"), MString("rio"), MFnData::kIntArray, aRmanIsOutput, &status ); MAKE_INPUT(tAttr); aRmanAccept = tAttr.create( MString("rmanAccept"), MString("rma"), MFnData::kStringArray, aRmanAccept, &status ); MAKE_INPUT(tAttr); aPreviewPrimitive = eAttr.create( "previewPrimitive", "pvp", 7, &status ); eAttr.addField( "Sphere", 0 ); eAttr.addField( "Cube", 1 ); eAttr.addField( "Cylinder", 2 ); eAttr.addField( "Torus", 3 ); eAttr.addField( "Plane", 4 ); eAttr.addField( "Teapot", 5 ); eAttr.addField( "Custom", 6 ); eAttr.addField( "(globals)",7 ); MAKE_NONKEYABLE_INPUT(eAttr); CHECK_MSTATUS(eAttr.setConnectable(false)); aPreviewCustomPrimitive = tAttr.create( MString("previewCustomPrimitive"), MString("pcp"), MFnData::kString, aPreviewCustomPrimitive, &status ); MAKE_INPUT(tAttr); aPreviewObjectSize = nAttr.create("previewObjectSize", "pos", MFnNumericData::kDouble, 1.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setConnectable(false)); aPreviewShadingRate = nAttr.create("previewShadingRate", "psr", MFnNumericData::kDouble, 1.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setConnectable(false)); aPreviewBackplane = nAttr.create("previewBackplane", "pbp", MFnNumericData::kBoolean, true, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setConnectable(false)); aShaderSpace = tAttr.create( MString("shaderSpace"), MString("ssp"), MFnData::kString, aShaderSpace, &status ); MAKE_INPUT(tAttr); aOutputInShadow = nAttr.create("outputInShadow", "ois", MFnNumericData::kBoolean, 0.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); // refreshPreview must be true to allow refresh aRefreshPreview = nAttr.create("refreshPreview", "rfp", MFnNumericData::kBoolean, 0.0, &status); MAKE_NONKEYABLE_INPUT(nAttr); CHECK_MSTATUS(nAttr.setHidden(true)); aPreviewGamma = nAttr.create( "previewGamma", "pg", MFnNumericData::kFloat, 1, &status ); CHECK_MSTATUS( status ); CHECK_MSTATUS( nAttr.setStorable( true ) ); CHECK_MSTATUS( nAttr.setHidden( true ) ); CHECK_MSTATUS( nAttr.setReadable( true ) ); CHECK_MSTATUS( nAttr.setDefault( 1.0f ) ); // Create output attributes aOutColor = nAttr.createColor("outColor", "oc"); MAKE_OUTPUT(nAttr); CHECK_MSTATUS(addAttribute(aRmanShader)); CHECK_MSTATUS(addAttribute(aRmanShaderType)); CHECK_MSTATUS(addAttribute(aRmanShaderLong)); CHECK_MSTATUS(addAttribute(aRmanShaderLif)); CHECK_MSTATUS(addAttribute(aRmanParams)); CHECK_MSTATUS(addAttribute(aRmanDetails)); CHECK_MSTATUS(addAttribute(aRmanTypes)); CHECK_MSTATUS(addAttribute(aRmanDefaults)); CHECK_MSTATUS(addAttribute(aRmanArraySizes)); CHECK_MSTATUS(addAttribute(aRmanLifCmds)); CHECK_MSTATUS(addAttribute(aRmanMethods)); CHECK_MSTATUS(addAttribute(aRmanIsOutput)); CHECK_MSTATUS(addAttribute(aRmanAccept)); CHECK_MSTATUS(addAttribute(aPreviewPrimitive)); CHECK_MSTATUS(addAttribute(aPreviewCustomPrimitive)); CHECK_MSTATUS(addAttribute(aPreviewObjectSize)); CHECK_MSTATUS(addAttribute(aPreviewShadingRate)); CHECK_MSTATUS(addAttribute(aPreviewBackplane)); CHECK_MSTATUS(addAttribute(aShaderSpace)); CHECK_MSTATUS(addAttribute(aOutputInShadow)); CHECK_MSTATUS(addAttribute(aRefreshPreview)); CHECK_MSTATUS(addAttribute(aPreviewGamma)); CHECK_MSTATUS(addAttribute(aOutColor)); return MS::kSuccess; }
// Constructor // viewCallbackTest::viewCallbackTest() { mPanelName = MString(""); mBufferOperation = kInvertColorBuffer; }
void TransformExport::Export() { ModelExporter & modelExporter = ModelExporter::GetExporter(); modelExporter.ResetTimeline(); MStatus stat; MItDependencyNodes itDep(MFn::kTransform,&stat); while (!itDep.isDone()) { MObject obj = itDep.item(); MFnTransform transform(obj, &stat); err_code(stat); MString cmd = MString("reference -q -f ") + transform.name(); MString file_id; stat = MGlobal::executeCommand( cmd, file_id ); if( stat == MS::kSuccess ) { itDep.next(); continue; } MString transformName = transform.name(&stat); err_code(stat); unsigned int parentCount = transform.parentCount(&stat); err_code(stat); unsigned int childCount = transform.childCount(&stat); err_code(stat); bool doExport = false; if (childCount == 0) { doExport = true; // Tip JOINTS } for (unsigned int child = 0 ; child < childCount ; child++) { MObject childObj = transform.child(child,&stat); err_code(stat); MFn::Type childType = childObj.apiType(); if ( modelExporter.CheckChildType(childType) ) { doExport = true; break; } } if (!doExport) { itDep.next(); continue; } TransformData * pTransformData = new TransformData(); pTransformData->name = transformName.asChar(); MObject parentObj = transform.parent(0,&stat); MFn::Type parentType = parentObj.apiType(); if ( modelExporter.CheckParentType(parentType) ) { MFnDagNode parentDagNode(parentObj, &stat); MString parentName = parentDagNode.name(&stat); if (parentName.length() > 0) pTransformData->parentName = parentName.asChar(); } if (parentType != MFn::kJoint && obj.apiType() == MFn::kJoint) { modelExporter.mSkeletonRoot = transform.name().asChar(); } MVector translate = transform.getTranslation(MSpace::kTransform, &stat); err_code(stat); MVector pivot = transform.rotatePivotTranslation(MSpace::kTransform, &stat); err_code(stat); pTransformData->tx = (float)translate.x; pTransformData->ty = (float)translate.y; pTransformData->tz = (float)translate.z; pTransformData->px = (float)pivot.x; pTransformData->py = (float)pivot.y; pTransformData->pz = (float)pivot.z; //double rx,ry,rz,rw; MQuaternion quat; stat = transform.getRotation(quat); err_code(stat); if (transform.object().hasFn(MFn::kJoint)) { err_code(stat); MFnIkJoint joint(transform.object(), &stat); err_code(stat); MQuaternion RO; MQuaternion R; MQuaternion JO; MQuaternion IS; // We dont have time for this. stat = joint.getScaleOrientation(RO); err_code(stat); stat = joint.getRotation(R); err_code(stat); stat = joint.getOrientation(JO); err_code(stat); quat = RO*R*JO; } //stat = transform.getRotationQuaternion(rx,ry,rz,rw, MSpace::kTransform); //err_code(stat); pTransformData->rx = -(float)quat.x; pTransformData->ry = -(float)quat.y; pTransformData->rz = -(float)quat.z; pTransformData->rw = (float)quat.w; double scale[3]; stat = transform.getScale(scale); err_code(stat); pTransformData->sx = (float)scale[0]; pTransformData->sy = (float)scale[1]; pTransformData->sz = (float)scale[2]; pTransformData->index = modelExporter.mTransformCount; modelExporter.mSceneTransforms.push_back(pTransformData); modelExporter.mSceneTransformsTable[transformName.asChar()] = modelExporter.mTransformCount; modelExporter.mTransformCount++; stat = itDep.next(); err_code(stat); } vector<TransformData*>::iterator nodesIter = modelExporter.mSceneTransforms.begin(); while (nodesIter != modelExporter.mSceneTransforms.end()) { TransformData * pTransformData = *nodesIter; if (pTransformData->parentName.length() > 0) pTransformData->parent = modelExporter.mSceneTransformsTable[pTransformData->parentName]; nodesIter++; } WriteTransforms(); }
virtual void ExportProcedural( AtNode *node ) { // do basic node export ExportMatrix( node, 0 ); // AiNodeSetPtr( node, "shader", arnoldShader(node) ); AiNodeSetInt( node, "visibility", ComputeVisibility() ); MPlug plug = FindMayaObjectPlug( "receiveShadows" ); if( !plug.isNull() ) { AiNodeSetBool( node, "receive_shadows", plug.asBool() ); } plug = FindMayaObjectPlug( "aiSelfShadows" ); if( !plug.isNull() ) { AiNodeSetBool( node, "self_shadows", plug.asBool() ); } plug = FindMayaObjectPlug( "aiOpaque" ); if( !plug.isNull() ) { AiNodeSetBool( node, "opaque", plug.asBool() ); } // now set the procedural-specific parameters AiNodeSetBool( node, "load_at_init", true ); // just for now so that it can load the shaders at the right time MFnDagNode fnDagNode( m_dagPath ); MBoundingBox bound = fnDagNode.boundingBox(); AiNodeSetPnt( node, "min", bound.min().x-m_dispPadding, bound.min().y-m_dispPadding, bound.min().z-m_dispPadding ); AiNodeSetPnt( node, "max", bound.max().x+m_dispPadding, bound.max().y, bound.max().z+m_dispPadding ); const char *dsoPath = getenv( "ALEMBIC_ARNOLD_PROCEDURAL_PATH" ); AiNodeSetStr( node, "dso", dsoPath ? dsoPath : "bb_AlembicArnoldProcedural.so" ); // Set the parameters for the procedural //abcFile path MString abcFile = fnDagNode.findPlug("cacheFileName").asString().expandEnvironmentVariablesAndTilde(); //object path MString objectPath = fnDagNode.findPlug("cacheGeomPath").asString(); //object pattern MString objectPattern = "*"; plug = FindMayaObjectPlug( "objectPattern" ); if (!plug.isNull() ) { if (plug.asString() != "") { objectPattern = plug.asString(); } } //object pattern MString excludePattern = ""; plug = FindMayaObjectPlug( "excludePattern" ); if (!plug.isNull() ) { if (plug.asString() != "") { excludePattern = plug.asString(); } } float shutterOpen = 0.0; plug = FindMayaObjectPlug( "shutterOpen" ); if (!plug.isNull() ) { shutterOpen = plug.asFloat(); } float shutterClose = 0.0; plug = FindMayaObjectPlug( "shutterClose" ); if (!plug.isNull() ) { shutterClose = plug.asFloat(); } float timeOffset = 0.0; plug = FindMayaObjectPlug( "timeOffset" ); if (!plug.isNull() ) { timeOffset = plug.asFloat(); } int subDIterations = 0; plug = FindMayaObjectPlug( "ai_subDIterations" ); if (!plug.isNull() ) { subDIterations = plug.asInt(); } MString nameprefix = ""; plug = FindMayaObjectPlug( "namePrefix" ); if (!plug.isNull() ) { nameprefix = plug.asString(); } // bool exportFaceIds = fnDagNode.findPlug("exportFaceIds").asBool(); bool makeInstance = true; // always on for now plug = FindMayaObjectPlug( "makeInstance" ); if (!plug.isNull() ) { makeInstance = plug.asBool(); } bool flipv = false; plug = FindMayaObjectPlug( "flipv" ); if (!plug.isNull() ) { flipv = plug.asBool(); } bool invertNormals = false; plug = FindMayaObjectPlug( "invertNormals" ); if (!plug.isNull() ) { invertNormals = plug.asBool(); } short i_subDUVSmoothing = 1; plug = FindMayaObjectPlug( "ai_subDUVSmoothing" ); if (!plug.isNull() ) { i_subDUVSmoothing = plug.asShort(); } MString subDUVSmoothing; switch (i_subDUVSmoothing) { case 0: subDUVSmoothing = "pin_corners"; break; case 1: subDUVSmoothing = "pin_borders"; break; case 2: subDUVSmoothing = "linear"; break; case 3: subDUVSmoothing = "smooth"; break; default : subDUVSmoothing = "pin_corners"; break; } MTime curTime = MAnimControl::currentTime(); // fnDagNode.findPlug("time").getValue( frame ); // MTime frameOffset; // fnDagNode.findPlug("timeOffset").getValue( frameOffset ); float time = curTime.as(MTime::kFilm)+timeOffset; MString argsString; if (objectPath != "|"){ argsString += "-objectpath "; // convert "|" to "/" argsString += MString(replace_all(objectPath,"|","/").c_str()); } if (objectPattern != "*"){ argsString += "-pattern "; argsString += objectPattern; } if (excludePattern != ""){ argsString += "-excludepattern "; argsString += excludePattern; } if (shutterOpen != 0.0){ argsString += " -shutteropen "; argsString += shutterOpen; } if (shutterClose != 0.0){ argsString += " -shutterclose "; argsString += shutterClose; } if (subDIterations != 0){ argsString += " -subditerations "; argsString += subDIterations; argsString += " -subduvsmoothing "; argsString += subDUVSmoothing; } if (makeInstance){ argsString += " -makeinstance "; } if (nameprefix != ""){ argsString += " -nameprefix "; argsString += nameprefix; } if (flipv){ argsString += " -flipv "; } if (invertNormals){ argsString += " -invertNormals "; } argsString += " -filename "; argsString += abcFile; argsString += " -frame "; argsString += time; if (m_displaced){ argsString += " -disp_map "; argsString += AiNodeGetName(m_dispNode); } AiNodeSetStr(node, "data", argsString.asChar()); ExportUserAttrs(node); // Export light linking per instance ExportLightLinking(node); }