MStatus skinClusterWeights::undoIt() { MStatus status; for (unsigned i = 0; i < fDagPathArray.length(); i++) { MDagPath &dagPath = fDagPathArray[i]; MObject skinCluster = findSkinCluster(dagPath); if (!isSkinClusterIncluded(skinCluster)) { continue; } MFnSkinCluster skinClusterFn(skinCluster, &status); if (status != MS::kSuccess) { continue; } MObject &component = fComponentArray[i]; if (dagPath.isValid() && fInfluenceIndexArrayPtrArray[i].length() > 0 && fWeightsPtrArray[i].length() > 0) { skinClusterFn.setWeights(dagPath, component, fInfluenceIndexArrayPtrArray[i], fWeightsPtrArray[i]); } } fDagPathArray.clear(); fComponentArray.clear(); delete [] fInfluenceIndexArrayPtrArray; delete [] fWeightsPtrArray; fInfluenceIndexArrayPtrArray = NULL; fWeightsPtrArray = NULL; return MS::kSuccess; }
MStatus HesperisCmd::writeSelectedCurve(const MSelectionList & selList) { MItSelectionList iter( selList ); MDagPathArray curves; MDagPathArray tms; for(; !iter.isDone(); iter.next()) { MDagPath apath; iter.getDagPath( apath ); tms.append(apath); ASearchHelper::LsAllTypedPaths(curves, apath, MFn::kNurbsCurve); } if(curves.length() < 1) { MGlobal::displayInfo(" zero curve selction!"); return MS::kSuccess; } HesperisFile hesf; bool fstat = hesf.create(m_fileName.asChar()); if(!fstat) { MGlobal::displayWarning(MString(" cannot create file ")+ m_fileName); return MS::kSuccess; } HesperisIO::WriteTransforms(tms, &hesf); HesperisCurveIO::WriteCurves(curves, &hesf); writeMesh(&hesf); MGlobal::displayInfo(" done."); return MS::kSuccess; }
void skinClusterWeights::populateInfluenceIndexArray(MFnSkinCluster &skinClusterFn, MIntArray &influenceIndexArray) { MStatus status; MIntArray allIndexArray; MDagPathArray pathArray; skinClusterFn.influenceObjects(pathArray, &status); for (unsigned j = 0; j < pathArray.length(); j++) { allIndexArray.append(skinClusterFn.indexForInfluenceObject(pathArray[j])); } if (influenceArray.length() > 0) { // Add the influence indices for the influence objects specified in the cmd for (unsigned j = 0; j < influenceArray.length(); j++) { unsigned int index = skinClusterFn.indexForInfluenceObject(influenceArray[j], &status); for (unsigned k = 0; k < allIndexArray.length(); k++) { if ((int)index == allIndexArray[k]) { influenceIndexArray.append(k); } } } } else { // Add the influence indices for all the influence objects of the skinCluster for (unsigned j = 0; j < allIndexArray.length(); j++) { influenceIndexArray.append(j); } } }
// -------------------------------------------------------------------- MStatus SceneGraph::addInstancedDagPaths ( MSelectionList& selectionList ) { MStatus status; int length = selectionList.length ( &status ); if ( status != MStatus::kSuccess ) return MStatus::kFailure; for ( int i=0; i<length; i++ ) { MDagPath dagPath; if ( selectionList.getDagPath ( i, dagPath ) != MStatus::kSuccess ) return MStatus::kFailure; if ( dagPath.isInstanced() ) { int includedInstance=dagPath.instanceNumber ( &status ); if ( status != MStatus::kSuccess ) return MStatus::kFailure; MObject object=dagPath.node ( &status ); if ( status != MStatus::kSuccess ) return MStatus::kFailure; MDagPathArray paths; if ( MDagPath::getAllPathsTo ( object, paths ) != MStatus::kSuccess ) return MStatus::kFailure; int numPaths=paths.length(); for ( int p=0; p<numPaths; p++ ) if ( p!=includedInstance ) selectionList.add ( paths[p] ); } } return MStatus::kSuccess; }
bool LiveScene::hasChild( const Name &name ) const { tbb::mutex::scoped_lock l( s_mutex ); if( m_dagPath.length() == 0 && !m_isRoot ) { throw Exception( "IECoreMaya::LiveScene::childNames: Dag path no longer exists!" ); } unsigned currentPathLength = m_dagPath.fullPathName().length(); MDagPathArray paths; getChildDags( m_dagPath, paths ); for( unsigned i=0; i < paths.length(); ++i ) { if( paths[i].hasFn( MFn::kTransform ) ) { std::string childName( paths[i].fullPathName().asChar() + currentPathLength + 1 ); if( Name( childName ) == name ) { return true; } } } return false; }
// -------------------------------------- ReferenceFile* ReferenceManager::processReferenceFile(const MString& filename) { ReferenceFile* file = new ReferenceFile(); file->filename = filename; mFiles.push_back(file); #if MAYA_API_VERSION >= 800 return file; // Versions 8.00 and 8.50 of Maya don't allow us to create references inside a plug-in. #elif MAYA_API_VERSION >= 600 // Get the original transformations for this file. // 1. Create a new reference MString tempFilename; MObject tempReferenceNode; { MString command = MString("file -r -type \"COLLADA importer\" -namespace \"_TEMP_EXP_NAMESPACE\" \"") + filename + "\";"; MGlobal::executeCommand(command, tempFilename); tempFilename = getLastReferenceFilename ( tempFilename ); MObject tempReferenceNode = getReferenceNode ( tempFilename ); MString tempNodeName = MFnDependencyNode(tempReferenceNode).name(); command = MString("file -loadReference \"") + tempNodeName + "\" \"" + tempFilename + "\";"; MGlobal::executeCommand(command); } // 2. Get the original transformations for the root transforms of the temporary reference object MDagPathArray tempRoots; MObjectArray subReferences; getRootObjects ( tempReferenceNode, tempRoots, subReferences ); uint tempRootCount = tempRoots.length(); for (uint j = 0; j < tempRootCount; ++j) { MFnTransform tempT(tempRoots[j]); file->originalTransformations.push_back( tempT.transformation() ); } // 3. Get the original node names. This will be used as the URL for export file->rootNames.setLength(tempRootCount); for (uint j = 0; j < tempRootCount; ++j) { MString& originalName = file->rootNames[j]; originalName = tempRoots[j].partialPathName(); originalName = originalName.substring ( originalName.index(':') + 1, originalName.length() ); } // 4. Cleanup: remove this reference MString command = MString("file -rr \"") + tempFilename + "\";"; MGlobal::executeCommand ( command ); #endif // MAYA >= 600 return file; }
void HesperisCmd::writeMesh(HesperisFile * file) { if(m_growMeshName.length() < 3) return; ASearchHelper searcher; MDagPath meshGrp; if(!searcher.dagByFullName(m_growMeshName.asChar(), meshGrp)) return; MDagPathArray meshes; ASearchHelper::LsAllTypedPaths(meshes, meshGrp, MFn::kMesh); if(meshes.length() < 1) MGlobal::displayInfo(MString(" no mesh found by name ")+m_growMeshName); HesperisIO::WriteMeshes(meshes, file); }
MStatus Molecule3Cmd::doIt( const MArgList &args ) { MStatus stat; // Initialize options to default values MFnTypedAttribute tAttr( /* radius.setValue( 0.1 ); segs = 6; ballRodRatio = 2.0; */ selMeshes.clear(); // Get the options from the command line MArgDatabase argData( syntax(), args, &stat ); if( !stat ) return stat; if( argData.isFlagSet( radiusFlag ) ) argData.getFlagArgument( radiusFlag, 0, radius ); if( argData.isFlagSet( segsFlag ) ) argData.getFlagArgument( segsFlag, 0, segs ); if( argData.isFlagSet( ballRatioFlag ) ) argData.getFlagArgument( ballRatioFlag, 0, ballRodRatio ); // Get a list of currently selected objects MSelectionList selection; MGlobal::getActiveSelectionList( selection ); // Iterate over the meshes MDagPath dagPath; MItSelectionList iter( selection, MFn::kMesh ); for ( ; !iter.isDone(); iter.next() ) { iter.getDagPath( dagPath ); selMeshes.append( dagPath ); } if( selMeshes.length() == 0 ) { MGlobal::displayWarning( "Select one or more meshes" ); return MS::kFailure; } return redoIt(); }
bool HesperisIO::GetCurves(const MDagPath &root, MDagPathArray & dst) { MStatus stat; MItDag iter; iter.reset(root, MItDag::kDepthFirst, MFn::kNurbsCurve); for(; !iter.isDone(); iter.next()) { MDagPath apath; iter.getPath( apath ); if(IsCurveValid(apath)) { MFnDagNode fdag(apath); if(!fdag.isIntermediateObject()) dst.append(apath); } } return dst.length() > 0; }
void LiveScene::getChildDags( const MDagPath& dagPath, MDagPathArray& paths ) const { for( unsigned i=0; i < dagPath.childCount(); ++i ) { MDagPath childPath = dagPath; childPath.push( dagPath.child( i ) ); if( dagPath.length() == 0 ) { // bizarrely, this iterates through things like the translate manipulator and // the view cube too, so lets skip them so they don't show up: if( childPath.node().hasFn( MFn::kManipulator3D ) ) { continue; } // looks like it also gives us the ground plane, so again, lets skip that: if( childPath.fullPathName() == "|groundPlane_transform" ) { continue; } } paths.append( childPath ); } }
bool isIn(const MDagPath & dagPath, const MObject & referenceNode) { MDagPathArray rootDagPaths; MObjectArray subReferences; ReferenceManager::getRootObjects(referenceNode, rootDagPaths, subReferences); for (unsigned int i = 0; i < rootDagPaths.length(); ++i) { if (rootDagPaths[i] == dagPath) { return true; } } for (unsigned int i = 0; i < subReferences.length(); ++i) { if (isIn(dagPath, subReferences[i])) { return true; } } return false; }
// ------------------------------------------------------------ void SceneGraph::addForcedNodes ( const MDagPath& dagPath ) { MFnMesh meshFn ( dagPath ); // Iterate upstream finding all the nodes which affect the mesh. MStatus stat; MPlug plug = meshFn.findPlug ( ATTR_IN_MESH ); if ( plug.isConnected() ) { MItDependencyGraph dependGraphIter ( plug, MFn::kInvalid, MItDependencyGraph::kUpstream, MItDependencyGraph::kDepthFirst, MItDependencyGraph::kPlugLevel, &stat ); if ( stat == MS::kSuccess ) { dependGraphIter.disablePruningOnFilter(); for ( ; ! dependGraphIter.isDone(); dependGraphIter.next() ) { MObject thisNode = dependGraphIter.thisNode(); MFn::Type type = thisNode.apiType(); if ( thisNode.apiType() == MFn::kSkinClusterFilter ) { MFnSkinCluster clusterFn ( thisNode ); MDagPathArray jointPaths; clusterFn.influenceObjects ( jointPaths, &stat ); if ( stat == MS::kSuccess ) { uint count = jointPaths.length(); for ( uint i = 0; i < count; ++i ) appendForcedNodeToList ( jointPaths[i] ); } } else if ( thisNode.apiType() == MFn::kJointCluster ) { MObject joint = DagHelper::getNodeConnectedTo ( thisNode, ATTR_MATRIX ); MDagPath jointPath = MDagPath::getAPathTo ( joint ); appendForcedNodeToList ( jointPath ); } } } } }
// ------------------------------------------------------------ void SceneGraph::findForcedNodes() { MStatus status; if ( mExportSelectedOnly ) { MSelectionList selectedItems; MGlobal::getActiveSelectionList ( selectedItems ); uint selectedCount = selectedItems.length(); MDagPathArray queue; for ( uint i = 0; i < selectedCount; ++i ) { MDagPath selectedPath; status = selectedItems.getDagPath ( i, selectedPath ); if ( status == MStatus::kSuccess ) queue.append ( selectedPath ); } while ( queue.length() > 0 ) { MDagPath selectedPath = queue[queue.length() - 1]; queue.remove ( queue.length() - 1 ); // Queue up the children. uint childCount = selectedPath.childCount(); for ( uint i = 0; i < childCount; ++i ) { MObject node = selectedPath.child ( i ); MDagPath childPath = selectedPath; childPath.push ( node ); queue.append ( childPath ); } // Look for a mesh if ( selectedPath.node().hasFn ( MFn::kMesh ) ) { // export forced nodes in path addForcedNodes ( selectedPath ); } } } else { for ( MItDag dagIt ( MItDag::kBreadthFirst ); !dagIt.isDone(); dagIt.next() ) { MDagPath currentPath; status = dagIt.getPath ( currentPath ); if ( status == MStatus::kSuccess ) { MFnDagNode node ( currentPath ); String nodeName = node.name().asChar(); if ( currentPath.node().hasFn ( MFn::kMesh ) ) { // export forced nodes in path addForcedNodes ( currentPath ); } } } } }
// // If a DAG node is instanced (i.e. has multiple parents), this method // will put it under its remaining parents. It will already have been put // under its first parent when it was created. // void maTranslator::writeInstances(fstream& f) { unsigned int numInstancedNodes = fInstanceChildren.length(); unsigned int i; for (i = 0; i < numInstancedNodes; i++) { MFnDagNode nodeFn(fInstanceChildren[i]); unsigned int numParents = nodeFn.parentCount(); unsigned int p; for (p = 0; p < numParents; p++) { // // We don't want to issue a 'parent' command for the node's // existing parent. // if (nodeFn.parent(i) != fInstanceParents[i].node()) { MObject parent = nodeFn.parent(i); MFnDagNode parentFn(parent); if (!parentFn.isFromReferencedFile()) { // // Get the first path to the parent node. // MDagPath parentPath; MDagPath::getAPathTo(parentFn.object(), parentPath); writeParent(f, parentPath, fInstanceChildren[i], true); } } } } // // We don't need this any more, so free up the space. // fInstanceChildren.clear(); fInstanceParents.clear(); }
// -------------------------------------- void ReferenceManager::getRootObjects( const MObject& referenceNode, MDagPathArray& rootPaths, MObjectArray& subReferences) { rootPaths.clear(); subReferences.clear(); MFnDependencyNode referenceNodeFn(referenceNode); // Get the paths of all the dag nodes included in this reference MStringArray nodeNames; MString command = MString("reference -rfn \"") + referenceNodeFn.name() + "\" -q -node -dp;"; MGlobal::executeCommand(command, nodeNames); uint nodeNameCount = nodeNames.length(); MDagPathArray nodePaths; for (uint j = 0; j < nodeNameCount; ++j) { MObject o = DagHelper::getNode(nodeNames[j]); MDagPath p = DagHelper::getShortestDagPath(o); if (p.length() > 0) { nodePaths.append(p); } else { if (o != MObject::kNullObj && o.apiType() == MFn::kReference && strstr(nodeNames[j].asChar(), "_UNKNOWN_REF_NODE") == NULL) { subReferences.append(o); } } } // Keep only the root transform for the reference in our path arrays uint nodePathCount = nodePaths.length(); for (uint j = 0; j < nodePathCount; ++j) { const MDagPath& p = nodePaths[j]; if ( !isRootTransform ( nodePaths, p ) ) continue; rootPaths.append(p); } }
//--------------------------------------------------- // Get a dag path or node from a String MDagPath DagHelper::getShortestDagPath ( const MObject& node ) { MDagPathArray paths; MDagPath::getAllPathsTo ( node, paths ); MDagPath shortestPath; if ( paths.length() > 0 ) { shortestPath = paths[0]; for ( uint i = 1; i < paths.length(); ++i ) { if ( shortestPath.length() > paths[i].length() ) { shortestPath = paths[i]; } } } return shortestPath; }
Imath::Box3d LiveScene::readBound( double time ) const { tbb::mutex::scoped_lock l( s_mutex ); if( fabs( MAnimControl::currentTime().as( MTime::kSeconds ) - time ) > 1.e-4 ) { throw Exception( "IECoreMaya::LiveScene::readBound: time must be the same as on the maya timeline!" ); } if( m_isRoot ) { MDagPathArray paths; getChildDags( m_dagPath, paths ); Imath::Box3d bound; for( unsigned i=0; i < paths.length(); ++i ) { MFnDagNode dagFn( paths[i] ); Imath::Box3d b = IECore::convert<Imath::Box3d, MBoundingBox>( dagFn.boundingBox() ); if( b.hasVolume() ) { bound.extendBy( b ); } } return bound; } else if( m_dagPath.length() == 0 ) { throw Exception( "IECoreMaya::LiveScene::readBound: Dag path no longer exists!" ); } else { MFnDagNode dagFn( m_dagPath ); Imath::Box3d ret = IECore::convert<Imath::Box3d, MBoundingBox>( dagFn.boundingBox() ); Imath::M44d invTransform = IECore::convert<Imath::M44d, MMatrix>( dagFn.transformationMatrix() ).inverse(); return Imath::transform( ret, invTransform ); } }
bool HesperisIO::CheckExistingCurves(CurveGroup * geos, MObject &target) { MDagPathArray existing; MDagPath root; MDagPath::getAPathTo(target, root); if(!GetCurves(root, existing)) return false; const unsigned ne = existing.length(); if(ne != geos->numCurves()) return false; unsigned n = 0; unsigned i=0; for(;i<ne;i++) { MFnNurbsCurve fcurve(existing[i].node()); n += fcurve.numCVs(); } if(n!=geos->numPoints()) return false; MGlobal::displayInfo(" existing curves matched"); return true; }
bool HesperisIO::WriteTransforms(const MDagPathArray & paths, HesperisFile * file, const std::string & beheadName) { file->setWriteComponent(HesperisFile::WTransform); file->setDirty(); unsigned i = 0; for(;i<paths.length();i++) AddTransform(paths[i], file, beheadName); bool fstat = file->save(); if(!fstat) MGlobal::displayWarning(MString(" cannot save transform to file ")+ file->fileName().c_str()); file->close(); return true; }
void MayaScene::childNames( NameList &childNames ) const { tbb::mutex::scoped_lock l( s_mutex ); if( m_dagPath.length() == 0 && !m_isRoot ) { throw Exception( "MayaScene::childNames: Dag path no longer exists!" ); } unsigned currentPathLength = m_dagPath.fullPathName().length(); MDagPathArray paths; getChildDags( m_dagPath, paths ); for( unsigned i=0; i < paths.length(); ++i ) { if( paths[i].hasFn( MFn::kTransform ) ) { std::string childName( paths[i].fullPathName().asChar() + currentPathLength + 1 ); childNames.push_back( Name( childName ) ); } } }
bool HesperisIO::CreateCurveGroup(MDagPathArray & paths, CurveGroup * dst) { MStatus stat; const unsigned n = paths.length(); unsigned i, j; int numCvs = 0; unsigned numNodes = 0; for(i=0; i< n; i++) { if(!IsCurveValid(paths[i])) continue; MFnNurbsCurve fcurve(paths[i].node()); numCvs += fcurve.numCVs(); numNodes++; } if(numCvs < 4) { MGlobal::displayInfo(" too fews cvs!"); return false; } dst->create(numNodes, numCvs); Vector3F * pnts = dst->points(); unsigned * counts = dst->counts(); unsigned inode = 0; unsigned icv = 0; unsigned nj; MPoint wp; MMatrix worldTm; for(i=0; i< n; i++) { if(!IsCurveValid(paths[i])) continue; worldTm = GetWorldTransform(paths[i]); MFnNurbsCurve fcurve(paths[i].node()); nj = fcurve.numCVs(); MPointArray ps; fcurve.getCVs(ps, MSpace::kWorld); counts[inode] = nj; inode++; for(j=0; j<nj; j++) { wp = ps[j] * worldTm; pnts[icv].set((float)wp.x, (float)wp.y, (float)wp.z); icv++; } } return true; }
void DXMNodeDagAdapter::Initialize(DXMNode* node) { DXMNodeAdapter::Initialize(node); if( g_DebugBasic ) { MFnDependencyNode depNode(node->GetSite()); MString name= depNode.name(); DXCC_DPFA_REPORT("%s", name.asChar()); } MDagPathArray dagPathArray; MFnDagNode dagNode(node->GetSite()); dagNode.getAllPaths(dagPathArray); for(UINT index= 0; index < dagPathArray.length(); index++) { AddRoute(dagPathArray[index]); } SyncFlags= DAGSYNC_TRANSFORM | DAGSYNC_VISIBILITY_OF_NODE | DAGSYNC_VISIBILITY_OF_ROUTES; GetOwnerGraphAdapter()->AddSyncRequest(this); }
bool HesperisPolygonalMeshIO::WritePolygonalMeshes(MDagPathArray & paths, HesperisFile * file) { std::vector<APolygonalMesh *> data; unsigned i = 0; for(;i<paths.length();i++) { APolygonalMesh * mesh = new APolygonalMesh; CreateMeshData(mesh, paths[i]); data.push_back(mesh); } std::vector<APolygonalMesh *>::iterator it = data.begin(); for(;it!=data.end(); ++it) delete *it; data.clear(); return true; }
// -------------------------------------- bool ReferenceManager::isRootTransform ( const MDagPathArray& allPaths, const MDagPath& testPath ) { MStatus status; MFnTransform transform(testPath, &status); if (status != MStatus::kSuccess) return false; uint pathCount = allPaths.length(); uint parentCount = transform.parentCount(); for (uint k = 0; k < parentCount; ++k) { MFnDependencyNode parentNode(transform.parent(k)); if (!parentNode.isFromReferencedFile()) continue; for (uint m = 0; m < pathCount; ++m) { if ( allPaths[m].node() == parentNode.object() ) return false; } } return true; }
MStatus Molecule3Cmd::redoIt() { MStatus stat; MDagPath dagPath; MFnMesh meshFn; // Create a ball int nBallPolys; MPointArray ballVerts; MIntArray ballPolyCounts; MIntArray ballPolyConnects; MFloatArray ballUCoords; MFloatArray ballVCoords; MIntArray ballFvUVIDs; genBall( MPoint::origin, ballRodRatio * radius.value(), segs, nBallPolys, ballVerts, ballPolyCounts, ballPolyConnects, true, ballUCoords, ballVCoords, ballFvUVIDs ); unsigned int i, j, vertOffset; MPointArray meshVerts; MPoint p0, p1; MObject objTransform; // Setup for rods int nRodPolys; MPointArray rodVerts; MIntArray rodPolyCounts; MIntArray rodPolyConnects; MFloatArray rodUCoords; MFloatArray rodVCoords; MIntArray rodFvUVIDs; // Setup for newMesh int nNewPolys; MPointArray newVerts; MIntArray newPolyCounts; MIntArray newPolyConnects; MFloatArray newUCoords; MFloatArray newVCoords; MIntArray newFvUVIDs; int uvOffset; MDagModifier dagMod; MFnDagNode dagFn; objTransforms.clear(); // Iterate over the meshes unsigned int mi; for( mi=0; mi < selMeshes.length(); mi++ ) { dagPath = selMeshes[mi]; meshFn.setObject( dagPath ); uvOffset = 0; nNewPolys = 0; newVerts.clear(); newPolyCounts.clear(); newPolyConnects.clear(); newUCoords.clear(); newVCoords.clear(); newFvUVIDs.clear(); // Generate balls meshFn.getPoints( meshVerts, MSpace::kWorld ); for( i=0; i < meshVerts.length(); i++ ) { vertOffset = newVerts.length(); // Add the ball to the new mesh nNewPolys += nBallPolys; // Move the ball vertices to the mesh vertex. Add it to the newMesh for( j=0; j < ballVerts.length(); j++ ) newVerts.append( meshVerts[i] + ballVerts[j] ); for( j=0; j < ballPolyCounts.length(); j++ ) newPolyCounts.append( ballPolyCounts[j] ); for( j=0; j < ballPolyConnects.length(); j++ ) newPolyConnects.append( vertOffset + ballPolyConnects[j] ); // Only add the uv coordinates once, since they are shared // by all balls if( i == 0 ) { for( j=0; j < ballUCoords.length(); j++ ) { newUCoords.append( ballUCoords[j] ); newVCoords.append( ballVCoords[j] ); } } for( j=0; j < ballFvUVIDs.length(); j++ ) { newFvUVIDs.append( uvOffset + ballFvUVIDs[j] ); } } uvOffset = newUCoords.length(); // Generate rods int nRods = 0; MItMeshEdge edgeIter( dagPath ); for( ; !edgeIter.isDone(); edgeIter.next(), nRods++ ) { p0 = edgeIter.point( 0, MSpace::kWorld ); p1 = edgeIter.point( 1, MSpace::kWorld ); // N.B. Generate the uv coordinates only once since they // are referenced by all rods genRod( p0, p1, radius.value(), segs, nRodPolys, rodVerts, rodPolyCounts, rodPolyConnects, nRods == 0, rodUCoords, rodVCoords, rodFvUVIDs ); vertOffset = newVerts.length(); // Add the rod to the mesh nNewPolys += nRodPolys; for( i=0; i < rodVerts.length(); i++ ) newVerts.append( rodVerts[i] ); for( i=0; i < rodPolyCounts.length(); i++ ) newPolyCounts.append( rodPolyCounts[i] ); for( i=0; i < rodPolyConnects.length(); i++ ) newPolyConnects.append( vertOffset + rodPolyConnects[i] ); // First rod if( nRods == 0 ) { // Add rod's uv coordinates to the list for( i=0; i < rodUCoords.length(); i++ ) { newUCoords.append( rodUCoords[i] ); newVCoords.append( rodVCoords[i] ); } } // Set the face-vertex-uvIDs for( i=0; i < rodFvUVIDs.length(); i++ ) { newFvUVIDs.append( uvOffset + rodFvUVIDs[i] ); } } objTransform = meshFn.create( newVerts.length(), nNewPolys, newVerts, newPolyCounts, newPolyConnects, newUCoords, newVCoords, MObject::kNullObj, &stat ); if( !stat ) { MGlobal::displayError( MString( "Unable to create mesh: " ) + stat.errorString() ); return stat; } objTransforms.append( objTransform ); meshFn.assignUVs( newPolyCounts, newFvUVIDs ); meshFn.updateSurface(); // Rename transform node dagFn.setObject( objTransform ); dagFn.setName( "molecule" ); // Put mesh into the initial shading group dagMod.commandToExecute( MString( "sets -e -fe initialShadingGroup " ) + meshFn.name() ); } // Select all the newly created molecule meshes MString cmd( "select -r" ); for( i=0; i < objTransforms.length(); i++ ) { dagFn.setObject( objTransforms[i] ); cmd += " " + dagFn.name(); } dagMod.commandToExecute( cmd ); return dagMod.doIt(); }
MStatus listLightLinks::doIt( const MArgList& args ) // // Description: // Implements the MEL listLightLinks command. After parsing the // information stored in Maya's light linker nodes, it examines // the first item on the selection list. If the item is an object, // then the command selects all lights that are linked to that object. // If the item is a light, then it will select all of the objects // that are linked to that light. // // Arguments: // args - The argument list that was passes to the command from MEL. // This command takes no arguments. // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - command failed (returning this value will cause the // MEL script that is being run to terminate unless the // error is caught using a "catch" statement. // { MStatus stat = MS::kSuccess; clearResult(); // Parse the links on the current scene's light linker node(s). // MLightLinks lightLink; bool parseStatus; parseStatus = lightLink.parseLinks(MObject::kNullObj); if( !parseStatus ) { setResult( "Error parsing light links\n" ); return MS::kFailure; } // Get the first object (or component) on the selection list. // MSelectionList selectList; MDagPath dagPath; MObject component; MGlobal::getActiveSelectionList( selectList ); selectList.getDagPath( 0, dagPath, component ); dagPath.extendToShape(); // Selection list to store entities linked to the selected light or // object. // MSelectionList newSelection; newSelection.clear(); // Stores the command result. // char resultString[512]; // If the object is a surface, we'll select all the lights linked to it. // If the object is a light, we'll select all the objects linked to it. // if( dagPath.hasFn( MFn::kLight ) ) { // Select objects linked to this light. // MSelectionList objects; objects.clear(); lightLink.getLinkedObjects( dagPath, objects ); newSelection.merge( objects ); sprintf( resultString, "Selecting objects linked to light %s", dagPath.fullPathName().asChar() ); } else { // Select lights linked to this object. // MDagPathArray lights; lights.clear(); lightLink.getLinkedLights( dagPath, component, lights ); for( unsigned int j = 0; j < lights.length(); j++ ) { const MDagPath& path = lights[j]; newSelection.add( path ); } sprintf( resultString, "Selecting lights linked to object %s", dagPath.fullPathName().asChar() ); } // Select the linked entities. // MGlobal::setActiveSelectionList( newSelection ); setResult( resultString ); return stat; }
MS DCTranslator::exportSelected() { MS status; MSelectionList selection; MGlobal::getActiveSelectionList(selection); MItSelectionList selIt(selection); if (selIt.isDone()) { status.perror("MayaToolKit: Nothing Selected!"); MGlobal::displayWarning("kaleido maya toolkit: Nothing selected!"); return MS::kFailure; } MDagPathArray pathArray; for (; !selIt.isDone(); selIt.next()) { MItDag dagIt(MItDag::kDepthFirst, MFn::kInvalid, &status); MDagPath objPath; status = selIt.getDagPath(objPath); status = dagIt.reset(objPath.node(), MItDag::kDepthFirst, MFn::kInvalid); do { MDagPath dagPath; MObject component = MObject::kNullObj; status = dagIt.getPath(dagPath); MFnDagNode dagNode(dagPath, &status); if (dagNode.isIntermediateObject()) { } else if (dagPath.hasFn(MFn::kMesh)) { if (!dagPath.hasFn(MFn::kTransform)) { SpMesh curMesh{ new Mesh }; status = GetMeshFromNode(dagPath, status, *curMesh); //WriteTheMesh Here if (status == MS::kSuccess) { (*m_MeshArch) << curMesh; MGlobal::displayInfo("Write Mesh finished."); m_Meshes.push_back(curMesh); } else { MGlobal::displayError("Error GetMesh From Node."); } } } else if (dagPath.hasFn(MFn::kCamera)) { if (!dagPath.hasFn(MFn::kTransform)) { pathArray.append(dagPath); } } else if (dagPath.hasFn(MFn::kSpotLight)) { if (!dagPath.hasFn(MFn::kTransform)) { pathArray.append(dagPath); } } dagIt.next(); } while (!dagIt.isDone()); } return status; }
bool ToMayaSkinClusterConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const { MStatus s; IECore::ConstSmoothSkinningDataPtr skinningData = IECore::runTimeCast<const IECore::SmoothSkinningData>( from ); assert( skinningData ); const std::vector<std::string> &influenceNames = skinningData->influenceNames()->readable(); const std::vector<Imath::M44f> &influencePoseData = skinningData->influencePose()->readable(); const std::vector<int> &pointIndexOffsets = skinningData->pointIndexOffsets()->readable(); const std::vector<int> &pointInfluenceCounts = skinningData->pointInfluenceCounts()->readable(); const std::vector<int> &pointInfluenceIndices = skinningData->pointInfluenceIndices()->readable(); const std::vector<float> &pointInfluenceWeights = skinningData->pointInfluenceWeights()->readable(); MFnDependencyNode fnSkinClusterNode( to, &s ); MFnSkinCluster fnSkinCluster( to, &s ); if ( s != MS::kSuccess ) { /// \todo: optional parameter to allow custom node types and checks for the necessary attributes /// \todo: create a new skinCluster if we want a kSkinClusterFilter and this isn't one throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid skinCluster" ) % fnSkinClusterNode.name() ).str() ); } const unsigned origNumInfluences = influenceNames.size(); unsigned numInfluences = origNumInfluences; std::vector<bool> ignoreInfluence( origNumInfluences, false ); std::vector<int> indexMap( origNumInfluences, -1 ); const bool ignoreMissingInfluences = m_ignoreMissingInfluencesParameter->getTypedValue(); const bool ignoreBindPose = m_ignoreBindPoseParameter->getTypedValue(); // gather the influence objects MObject mObj; MDagPath path; MSelectionList influenceList; MDagPathArray influencePaths; for ( unsigned i=0, index=0; i < origNumInfluences; i++ ) { MString influenceName( influenceNames[i].c_str() ); s = influenceList.add( influenceName ); if ( !s ) { if ( ignoreMissingInfluences ) { ignoreInfluence[i] = true; MGlobal::displayWarning( MString( "ToMayaSkinClusterConverter: \"" + influenceName + "\" is not a valid influence" ) ); continue; } throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid influence" ) % influenceName ).str() ); } influenceList.getDependNode( index, mObj ); MFnIkJoint fnInfluence( mObj, &s ); if ( !s ) { if ( ignoreMissingInfluences ) { ignoreInfluence[i] = true; influenceList.remove( index ); MGlobal::displayWarning( MString( "ToMayaSkinClusterConverter: \"" + influenceName + "\" is not a valid influence" ) ); continue; } throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid influence" ) % influenceName ).str() ); } fnInfluence.getPath( path ); influencePaths.append( path ); indexMap[i] = index; index++; } MPlugArray connectedPlugs; bool existingBindPose = true; MPlug bindPlug = fnSkinClusterNode.findPlug( "bindPose", true, &s ); if ( !bindPlug.connectedTo( connectedPlugs, true, false ) ) { existingBindPose = false; if ( !ignoreBindPose ) { throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" does not have a valid bindPose" ) % fnSkinClusterNode.name() ).str() ); } } MPlug bindPoseMatrixArrayPlug; MPlug bindPoseMemberArrayPlug; if ( existingBindPose ) { MFnDependencyNode fnBindPose( connectedPlugs[0].node() ); if ( fnBindPose.typeName() != "dagPose" ) { throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid bindPose" ) % fnBindPose.name() ).str() ); } bindPoseMatrixArrayPlug = fnBindPose.findPlug( "worldMatrix", true, &s ); bindPoseMemberArrayPlug = fnBindPose.findPlug( "members", true, &s ); } /// \todo: optional parameter to reset the skinCluster's geomMatrix plug // break existing influence connections to the skinCluster MDGModifier dgModifier; MMatrixArray ignoredPreMatrices; MPlug matrixArrayPlug = fnSkinClusterNode.findPlug( "matrix", true, &s ); MPlug bindPreMatrixArrayPlug = fnSkinClusterNode.findPlug( "bindPreMatrix", true, &s ); for ( unsigned i=0; i < matrixArrayPlug.numConnectedElements(); i++ ) { MPlug matrixPlug = matrixArrayPlug.connectionByPhysicalIndex( i, &s ); matrixPlug.connectedTo( connectedPlugs, true, false ); if ( !connectedPlugs.length() ) { continue; } MFnIkJoint fnInfluence( connectedPlugs[0].node() ); fnInfluence.getPath( path ); if ( ignoreMissingInfluences && !influenceList.hasItem( path ) ) { MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i ); preMatrixPlug.getValue( mObj ); MFnMatrixData matFn( mObj ); ignoredPreMatrices.append( matFn.matrix() ); ignoreInfluence.push_back( false ); indexMap.push_back( influenceList.length() ); influenceList.add( connectedPlugs[0].node() ); numInfluences++; } dgModifier.disconnect( connectedPlugs[0], matrixPlug ); } MPlug lockArrayPlug = fnSkinClusterNode.findPlug( "lockWeights", true, &s ); for ( unsigned i=0; i < lockArrayPlug.numConnectedElements(); i++ ) { MPlug lockPlug = lockArrayPlug.connectionByPhysicalIndex( i, &s ); lockPlug.connectedTo( connectedPlugs, true, false ); if ( connectedPlugs.length() ) { dgModifier.disconnect( connectedPlugs[0], lockPlug ); } } MPlug paintPlug = fnSkinClusterNode.findPlug( "paintTrans", true, &s ); paintPlug.connectedTo( connectedPlugs, true, false ); if ( connectedPlugs.length() ) { dgModifier.disconnect( connectedPlugs[0], paintPlug ); } // break existing influence connections to the bind pose if ( existingBindPose ) { for ( unsigned i=0; i < bindPoseMatrixArrayPlug.numConnectedElements(); i++ ) { MPlug matrixPlug = bindPoseMatrixArrayPlug.connectionByPhysicalIndex( i, &s ); matrixPlug.connectedTo( connectedPlugs, true, false ); if ( connectedPlugs.length() ) { dgModifier.disconnect( connectedPlugs[0], matrixPlug ); } } for ( unsigned i=0; i < bindPoseMemberArrayPlug.numConnectedElements(); i++ ) { MPlug memberPlug = bindPoseMemberArrayPlug.connectionByPhysicalIndex( i, &s ); memberPlug.connectedTo( connectedPlugs, true, false ); if ( connectedPlugs.length() ) { dgModifier.disconnect( connectedPlugs[0], memberPlug ); } } } if ( !dgModifier.doIt() ) { dgModifier.undoIt(); throw IECore::Exception( "ToMayaSkinClusterConverter: Unable to break the influence connections" ); } // make connections from influences to skinCluster and bindPose for ( unsigned i=0; i < numInfluences; i++ ) { if ( ignoreInfluence[i] ) { continue; } int index = indexMap[i]; s = influenceList.getDependNode( index, mObj ); MFnIkJoint fnInfluence( mObj, &s ); MPlug influenceMatrixPlug = fnInfluence.findPlug( "worldMatrix", true, &s ).elementByLogicalIndex( 0, &s ); MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s ); MPlug influenceBindPosePlug = fnInfluence.findPlug( "bindPose", true, &s ); MPlug influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s ); if ( !s ) { // add the lockInfluenceWeights attribute if it doesn't exist MFnNumericAttribute nAttr; MObject attribute = nAttr.create( "lockInfluenceWeights", "liw", MFnNumericData::kBoolean, false ); fnInfluence.addAttribute( attribute ); influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s ); } // connect influence to the skinCluster MPlug matrixPlug = matrixArrayPlug.elementByLogicalIndex( index ); MPlug lockPlug = lockArrayPlug.elementByLogicalIndex( index ); dgModifier.connect( influenceMatrixPlug, matrixPlug ); dgModifier.connect( influenceLockPlug, lockPlug ); // connect influence to the bindPose if ( !ignoreBindPose ) { MPlug bindPoseMatrixPlug = bindPoseMatrixArrayPlug.elementByLogicalIndex( index ); MPlug memberPlug = bindPoseMemberArrayPlug.elementByLogicalIndex( index ); dgModifier.connect( influenceMessagePlug, bindPoseMatrixPlug ); dgModifier.connect( influenceBindPosePlug, memberPlug ); } } unsigned firstIndex = find( ignoreInfluence.begin(), ignoreInfluence.end(), false ) - ignoreInfluence.begin(); influenceList.getDependNode( firstIndex, mObj ); MFnDependencyNode fnInfluence( mObj ); MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s ); dgModifier.connect( influenceMessagePlug, paintPlug ); if ( !dgModifier.doIt() ) { dgModifier.undoIt(); throw IECore::Exception( "ToMayaSkinClusterConverter: Unable to create the influence connections" ); } // use influencePoseData as bindPreMatrix for ( unsigned i=0; i < numInfluences; i++ ) { if ( ignoreInfluence[i] ) { continue; } MMatrix preMatrix = ( i < origNumInfluences ) ? IECore::convert<MMatrix>( influencePoseData[i] ) : ignoredPreMatrices[i-origNumInfluences]; MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( indexMap[i], &s ); s = preMatrixPlug.getValue( mObj ); if ( s ) { MFnMatrixData matFn( mObj ); matFn.set( preMatrix ); mObj = matFn.object(); } else { MFnMatrixData matFn; mObj = matFn.create( preMatrix ); } preMatrixPlug.setValue( mObj ); } // remove unneeded bindPreMatrix children unsigned existingElements = bindPreMatrixArrayPlug.numElements(); for ( unsigned i=influenceList.length(); i < existingElements; i++ ) { MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i, &s ); /// \todo: surely there is a way to accomplish this in c++... MGlobal::executeCommand( ( boost::format( "removeMultiInstance %s" ) % preMatrixPlug.name() ).str().c_str() ); } // get the geometry MObjectArray outputGeoObjs; if ( !fnSkinCluster.getOutputGeometry( outputGeoObjs ) ) { throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: skinCluster \"%s\" does not have any output geometry!" ) % fnSkinCluster.name() ).str() ); } MFnDagNode dagFn( outputGeoObjs[0] ); MDagPath geoPath; dagFn.getPath( geoPath ); // loop through all the points of the geometry and set the weights MItGeometry geoIt( outputGeoObjs[0] ); MPlug weightListArrayPlug = fnSkinClusterNode.findPlug( "weightList", true, &s ); for ( unsigned pIndex=0; !geoIt.isDone(); geoIt.next(), pIndex++ ) { MPlug pointWeightsPlug = weightListArrayPlug.elementByLogicalIndex( pIndex, &s ).child( 0 ); // remove existing influence weight plugs MIntArray existingInfluenceIndices; pointWeightsPlug.getExistingArrayAttributeIndices( existingInfluenceIndices ); for( unsigned i=0; i < existingInfluenceIndices.length(); i++ ) { MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( existingInfluenceIndices[i], &s ); MGlobal::executeCommand( ( boost::format( "removeMultiInstance -break 1 %s" ) % influenceWeightPlug.name() ).str().c_str() ); } // add new influence weight plugs int firstIndex = pointIndexOffsets[pIndex]; for( int i=0; i < pointInfluenceCounts[pIndex]; i++ ) { int influenceIndex = pointInfluenceIndices[ firstIndex + i ]; if ( ignoreInfluence[ influenceIndex ] ) { continue; } int skinClusterInfluenceIndex = fnSkinCluster.indexForInfluenceObject( influencePaths[ indexMap[ influenceIndex ] ] ); MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( skinClusterInfluenceIndex, &s ); influenceWeightPlug.setValue( pointInfluenceWeights[ firstIndex + i ] ); } } return true; }
// // Given a list of 3 paths and compoents find the face they define and store their indices // MStatus meshMapUtils::validateFaceSelection( MDagPathArray& paths, MObjectArray& components, int *faceIdx, MIntArray *seedVtx ) { MStatus stat = MStatus::kSuccess; MIntArray finalFaceList; if ( paths.length() != 3 || components.length() != 3 ) { return MStatus::kFailure; } seedVtx->clear(); for (unsigned int i = 0; i < 3; i++) { MItMeshVertex fIt ( paths[i], components[i], &stat ); if( stat != MStatus::kSuccess || fIt.isDone() ) { MGlobal::displayError( " MItMeshVertex failed"); return MStatus::kFailure; } seedVtx->append( fIt.index() ); // The cv's location MIntArray faceList; stat = fIt.getConnectedFaces ( faceList ); if( stat != MStatus::kSuccess ) { MGlobal::displayError( " getConnectedFaces failed"); return MStatus::kFailure; } if( i == 0 ) { finalFaceList = faceList; } else { meshMapUtils::intersectArrays( finalFaceList, faceList ); } } if( finalFaceList.length() != 1 ) { return MStatus::kFailure; } else { *faceIdx = finalFaceList[0]; } MDagPath p0( paths[0] ); MDagPath p1( paths[1] ); MDagPath p2( paths[2] ); if( !(p0 == p1 ) || !(p0 == p2 )) { return MStatus::kFailure; } return MStatus::kSuccess; }
// ------------------------------------------------------------ bool SceneGraph::retrieveExportNodes() { // Create a selection list containing only the root nodes (implies export all!) MSelectionList allTargets; for ( MItDag it ( MItDag::kBreadthFirst ); it.depth()<=1 && it.item()!=MObject::kNullObj; it.next() ) { MDagPath path; MStatus status = it.getPath ( path ); String pathName = path.fullPathName().asChar(); // Attach a function set MFnDependencyNode fn ( path.node() ); String theNodeName = fn.name().asChar(); // Check if it's the world node if ( it.depth() == 0 ) continue; if ( status == MStatus::kSuccess ) { if ( mExportSelectedOnly ) allTargets.add ( path ); else mTargets.add ( path ); } } // now fill in the targets, either the same as allTargets, or it is export selection only if ( mExportSelectedOnly ) { // Export the selection: // Grab the selected DAG components if ( MStatus::kFailure == MGlobal::getActiveSelectionList ( mTargets ) ) { std::cerr << "MGlobal::getActiveSelectionList" << std::endl; return false; } // For all the non-transforms selected, make sure to extend to the transforms underneath. MDagPathArray additions; MIntArray removals; for ( uint32 i = 0; i < mTargets.length(); ++i ) { MDagPath itemPath; mTargets.getDagPath ( i, itemPath ); if ( !itemPath.node().hasFn ( MFn::kTransform ) ) { MDagPath transformPath = itemPath; while ( transformPath.length() > 0 ) { transformPath.pop(); if ( !mTargets.hasItem ( transformPath ) ) { additions.append ( transformPath ); break; } } removals.append ( i ); } } for ( uint32 i = 0; i < removals.length(); ++i ) mTargets.remove ( removals[i] - i ); for ( uint32 i = 0; i < additions.length(); ++i ) mTargets.add ( additions[i] ); // Add all the forced nodes to the list. uint32 forceNodeCount = mForcedNodes.length(); for ( uint32 i = 0; i < forceNodeCount; ++i ) { MDagPath p = mForcedNodes[i]; if ( mTargets.hasItem ( p ) ) continue; mTargets.add ( p ); } // Add additional selection paths for any objects in our // selection which have been instanced (either directly, or // via instancing of an ancestor) - as otherwise, the selection // will only include ONE of the DAG paths // addInstancedDagPaths ( mTargets ); // remove any selected nodes CONTAINED within other selected // hierarchies (to ensure we don't export subtrees multiple times) // removeMultiplyIncludedDagPaths ( mTargets ); } return true; }