//====================================================================== // // Check the parsed arguments and do/undo/redo the command as appropriate // void checkArgs(ref MArgDatabase argsDb) { MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (uint i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { fMesh = new MFnMesh(obj); fObj = obj; fObjTransform = dagPath.node; } } if( fMesh == null || fObj == null || fObjTransform == null ) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); throw new ArgumentException(errMsg, "argsDb"); } }
override public void redoIt() { _dagModifier.doIt(); var dagFn = new MFnDagNode(_transform); _shape = dagFn.child(0); _dagModifier.renameNode(_shape, "motionCameraShape"); _dagModifier.doIt(); }
/// <summary> /// Return the bones to export. /// </summary> /// <param name="skin">the skin to export</param> /// <returns>Array of BabylonBone to export</returns> private BabylonBone[] ExportBones(MFnSkinCluster skin) { int logRank = 1; int skinIndex = GetSkeletonIndex(skin); List <BabylonBone> bones = new List <BabylonBone>(); Dictionary <string, int> indexByFullPathName = GetIndexByFullPathNameDictionary(skin); List <MObject> revelantNodes = GetRevelantNodes(skin); progressBoneStep = progressSkinStep / revelantNodes.Count; foreach (MObject node in revelantNodes) { MFnDagNode dagNode = new MFnDagNode(node); MFnTransform currentNodeTransform = new MFnTransform(node); string currentFullPathName = dagNode.fullPathName; int index = indexByFullPathName[currentFullPathName]; int parentIndex = -1; // find the parent node to get its index if (!dagNode.parent(0).hasFn(MFn.Type.kWorld)) { MFnTransform firstParentTransform = new MFnTransform(dagNode.parent(0)); parentIndex = indexByFullPathName[firstParentTransform.fullPathName]; } // create the bone BabylonBone bone = new BabylonBone() { id = currentNodeTransform.uuid().asString(), name = dagNode.name, index = indexByFullPathName[currentFullPathName], parentBoneIndex = parentIndex, matrix = GetBabylonMatrix(currentNodeTransform, frameBySkeletonID[skinIndex]).m, animation = GetAnimationsFrameByFrameMatrix(currentNodeTransform) }; bones.Add(bone); RaiseVerbose($"Bone: name={bone.name}, index={bone.index}, parentBoneIndex={bone.parentBoneIndex}, matrix={string.Join(" ", bone.matrix)}", logRank + 1); // Progress bar progressSkin += progressBoneStep; ReportProgressChanged(progressSkin); CheckCancelled(); } // sort List <BabylonBone> sorted = new List <BabylonBone>(); sorted = bones.OrderBy(bone => bone.index).ToList(); bones = sorted; RaiseMessage($"{bones.Count} bone(s) exported", logRank + 1); return(bones.ToArray()); }
//====================================================================== // // Look through the arg database and verify that the arguments are // valid. Only checks the common flags so derived classes should call // this parent method first before checking their own flags. // public virtual void checkArgs(MArgDatabase argsDb) { String formatType = "raw"; fSerialize = AssociationsSerializer.formatByName( formatType ); if( fSerialize == null) { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kMetadataFormatNotFound); String msg = String.Format(fmt, formatType); displayError(msg); throw new System.ArgumentException(msg); } //---------------------------------------- // (selection list) // // Commands need at least one mesh object on which to operate so gather up // the list of meshes specified and/or selected. // // Empty out the list of meshes on which to operate so that it can be // populated from the selection or specified lists. fMeshes.clear(); MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (int i = 0; i<objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode( dagPath.node ); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { MFnMesh mesh = new MFnMesh(obj); if(mesh != null) fMeshes.append(obj); } else { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError); String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]"); displayError(msg); throw new System.InvalidOperationException(msg); } } if( fMeshes.length == 0 ) { String msg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); displayError(msg); throw new System.InvalidOperationException(msg); } }
public void sendCurveToMaya(string node_name, Point3DCollection controlVertices, List <double> knots, int degree, MFnNurbsCurveForm form) { var dn = new MFnDagNode(getDagNode(node_name)); var plCreate = dn.findPlug("create"); var plDynamoCreate = new MPlug(); try { plDynamoCreate = dn.findPlug("dynamoCreate"); } catch { var tAttr = new MFnTypedAttribute(); var ldaDynamoCreate = tAttr.create("dynamoCreate", "dc", MFnData.Type.kNurbsCurve, MObject.kNullObj); try { dn.addAttribute(ldaDynamoCreate, MFnDependencyNode.MAttrClass.kLocalDynamicAttr); plDynamoCreate = dn.findPlug(ldaDynamoCreate); var dagm = new MDagModifier(); dagm.connect(plDynamoCreate, plCreate); dagm.doIt(); } catch { return; } } var ncd = new MFnNurbsCurveData(); var oOwner = ncd.create(); var nc = new MFnNurbsCurve(); var p_aControlVertices = new MPointArray(); foreach (var p in controlVertices) { p_aControlVertices.Add(new MPoint(p.X, p.Y, p.Z)); } var d_aKnots = new MDoubleArray(); for (var i = 1; i < knots.Count - 1; ++i) { d_aKnots.Add(knots[i]); } nc.create(p_aControlVertices, d_aKnots, (uint)degree, (MFnNurbsCurve.Form)form, false, true, oOwner); plDynamoCreate.setMObject(oOwner); MGlobal.executeCommandOnIdle(string.Format("dgdirty {0}.create;", node_name)); }
private void buildXformTree() { // Get the very root of the Maya DAG. MItDag rootIt = new MItDag(); rootXform.isRoot = true; rootXform.name = "root"; MFnDagNode rootDagNode = new MFnDagNode(rootIt.root()); rootDagNode.getPath(rootXform.mayaObjectPath); // Process all children transforms of the root. processXform(rootXform); }
private void ExportNode(BabylonAbstractMesh babylonAbstractMesh, MFnDagNode mFnDagNode, BabylonScene babylonScene) { if (mFnDagNode.parentCount != 0) { MObject parentMObject = mFnDagNode.parent(0); MFnDagNode mFnDagNodeParent = new MFnDagNode(parentMObject); // Position / rotation / scaling ExportTransform(babylonAbstractMesh, mFnDagNodeParent); // TODO - Hierarchy //babylonAbstractMesh.parentId = mFnDagNodeParent.uuid().asString(); } }
void printTransformData(MDagPath dagPath, bool quiet) { MObject transformNode = null; try { transformNode = dagPath.transform; } catch (System.Exception) { // This node has no transform - i.e., it's the world node // return; } MFnDagNode transform = null; try { transform = new MFnDagNode(transformNode); } catch (System.Exception) { return; } MTransformationMatrix matrix = new MTransformationMatrix(transform.transformationMatrix); if (!quiet) { MGlobal.displayInfo(" translation: " + MVectorToString(matrix.translation(MSpace.Space.kWorld)) + Environment.NewLine); } double[] threeDoubles = new double[3]; int rOrder = 0; matrix.getRotation(threeDoubles, out rOrder, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" rotation: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } matrix.getScale(threeDoubles, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" scale: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } }
private void ExportHierarchy(BabylonNode babylonNode, MFnTransform mFnTransform) { if (mFnTransform.parentCount != 0) { RaiseVerbose("BabylonExporter.Node | Hierarchy", 2); MObject parentMObject = mFnTransform.parent(0); // Children of World node don't have parent in Babylon if (parentMObject.apiType != MFn.Type.kWorld) { MFnDagNode mFnTransformParent = new MFnDagNode(parentMObject); babylonNode.parentId = mFnTransformParent.uuid().asString(); } } }
// The implementation here is a bit different from its counterpart C++ sample because // .NET SDK decides not to support the obsolete C++ API: // // bool connectTargetAttribute (void *opaqueTarget, int index, MObject &constraintAttr); // protected override bool connectTarget(MDagPath targetPath, int index) { try { MObject targetObject = new MObject(targetPath.node); MFnDagNode targetDagNode = new MFnDagNode(targetObject); connectTargetAttribute(targetPath, index, targetDagNode.attribute("worldMesh"), GeometrySurfaceConstraint.targetGeometry); } catch (Exception) { MGlobal.displayError("Failed to connect target."); return(false); } return(true); }
public List<string> getMayaNodesByType(MFnType t) { List<string> lMayaNodes = new List<string>(); MItDag itdagn = new MItDag(MItDag.TraversalType.kBreadthFirst, (MFn.Type)t); MFnDagNode dagn; while (!itdagn.isDone) { dagn = new MFnDagNode(itdagn.item()); if(!dagn.isIntermediateObject) lMayaNodes.Add(dagn.partialPathName); itdagn.next(); } return lMayaNodes; }
// Decide if the dag is in the model. Dag paths and names // may not be setup if the dag has not been added to // the model. private static bool dagNotInModel(MDagPath dagPath) { MFnDagNode dagFn; bool inModel; try { dagFn = new MFnDagNode(dagPath); inModel = dagFn.inModel; } catch (System.Exception) { return(false); } return(inModel == false); }
/// <summary> /// Compare two Maya nodes. /// </summary> /// <param name="mObject1">First Maya node</param> /// <param name="mObject2">Seconde Maya node</param> /// <returns> /// True, if the two Maya nodes are equal. /// False, otherwise /// </returns> private bool Equals(MObject mObject1, MObject mObject2) { if (mObject1 == mObject2) { return(true); } if (mObject1 == null || mObject2 == null) { return(false); } MFnDagNode node1 = new MFnDagNode(mObject1); MFnDagNode node2 = new MFnDagNode(mObject2); return(node1.fullPathName.Equals(node2.fullPathName)); }
//====================================================================== // // Check the parsed arguments and do/undo/redo the command as appropriate // void checkArgs(ref MArgDatabase argsDb) { //---------------------------------------- // (selection list) // // Commands need at least one node on which to operate so gather up // the list of nodes specified and/or selected. // // Empty out the list of nodes on which to operate so that it can be // populated from the selection or specified lists. fNodes.clear(); MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (uint i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { if (obj == MObject.kNullObj) { throw new ApplicationException("Error: objects.getDependNode() "); } fNodes.append(dagPath.node); } else { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError); String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]"); displayError(msg); throw new System.InvalidOperationException(msg); } } if (fNodes.length == 0) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); throw new ArgumentException(errMsg, "argsDb"); } }
private void setMeshData(MObject transform, MObject dataWrapper) { // Get the mesh node. MFnDagNode dagFn = new MFnDagNode(transform); MObject mesh = dagFn.child(0); // The mesh node has two geometry inputs: 'inMesh' and 'cachedInMesh'. // 'inMesh' is only used when it has an incoming connection, otherwise // 'cachedInMesh' is used. Unfortunately, the docs say that 'cachedInMesh' // is for internal use only and that changing it may render Maya // unstable. // // To get around that, we do the little dance below... // Use a temporary MDagModifier to create a temporary mesh attribute on // the node. MFnTypedAttribute tAttr = new MFnTypedAttribute(); MObject tempAttr = tAttr.create("tempMesh", "tmpm", MFnData.Type.kMesh); MDagModifier tempMod = new MDagModifier(); tempMod.addAttribute(mesh, tempAttr); tempMod.doIt(); // Set the geometry data onto the temp attribute. dagFn.setObject(mesh); MPlug tempPlug = dagFn.findPlug(tempAttr); tempPlug.setValue(dataWrapper); // Use the temporary MDagModifier to connect the temp attribute to the // node's 'inMesh'. MPlug inMeshPlug = dagFn.findPlug("inMesh"); tempMod.connect(tempPlug, inMeshPlug); tempMod.doIt(); // Force the mesh to update by grabbing its output geometry. dagFn.findPlug("outMesh").asMObject(); // Undo the temporary modifier. tempMod.undoIt(); }
/* * static Action m_update= delegate { }; * public void SubscribeEvent() * { * IEvents subscriber = OperationContext.Current.GetCallbackChannel<IEvents>(); * m_update += subscriber.hasUpdated; * } * * public static void SendUpdateEvent() * { * m_update(); * } * * public void UpdateEvent() * { * ServiceImplementation.SendUpdateEvent(); * } */ public List <string> getMayaNodesByType(MFnType t) { var lMayaNodes = new List <string>(); var itdagn = new MItDag(MItDag.TraversalType.kBreadthFirst, (MFn.Type)t); MFnDagNode dagn; while (!itdagn.isDone) { dagn = new MFnDagNode(itdagn.item()); if (!dagn.isIntermediateObject) { lMayaNodes.Add(dagn.partialPathName); } itdagn.next(); } return(lMayaNodes); }
private void ExportTransform(BabylonAbstractMesh babylonAbstractMesh, MFnDagNode mFnDagNode) { // Position / rotation / scaling var transformationMatrix = new MTransformationMatrix(mFnDagNode.transformationMatrix); babylonAbstractMesh.position = transformationMatrix.getTranslation(); if (_exportQuaternionsInsteadOfEulers) { babylonAbstractMesh.rotationQuaternion = transformationMatrix.getRotationQuaternion(); } else { babylonAbstractMesh.rotation = transformationMatrix.getRotation(); } babylonAbstractMesh.scaling = transformationMatrix.getScale(); }
private void linkXformsMeshes() { foreach (MayaXform xform in allXforms) { // Convert to a DAG node to traverse children. MFnDagNode dagNode = new MFnDagNode(xform.mayaObjectPath); for (uint childIdx = 0; childIdx < dagNode.childCount; ++childIdx) { MObject childObj = dagNode.child(childIdx); // If the child has a mesh, link it. if (childObj.hasFn(MFn.Type.kMesh)) { xform.mesh = pathMeshMap[(new MFnMesh(childObj)).fullPathName]; break; } } } }
internal void MObjOnChanged(object sender, MFnDagNode dagNode) { if (!isUpdating) { isUpdating = true; var dag = new DMCurve(dagNode.dagPath, space); // if (liveUpdate) // { isFromUpdate = true; if (SelectedItems.ContainsKey(dag.dagName)) { SelectedItems[dag.dagName] = dag; dynamoElement[dag.dagName] = AstFactory.BuildFunctionCall( dynamoElementFunc, new List <AssociativeNode> { AstFactory.BuildStringNode(dag.dagName), AstFactory.BuildStringNode(m_mSpace) }); /* * mayaGeom[dag.dagName] = AstFactory.BuildFunctionCall( * MayaElementFunc, * new List<AssociativeNode> * { * AstFactory.BuildStringNode(dag.dagName), * AstFactory.BuildStringNode(m_mSpace) * });*/ } OnNodeModified(true); //} // else // { // MarkNodeAsModified(true); // } } }
private void processXform(MayaXform xform) { // Add the current Xform to the list of all xforms. allXforms.Add(xform); // Set the Xform's id. xform.id = allXforms.Count - 1; // Add the current Xform to the map based on its path. pathXformMap[xform.name] = xform; // Build data for this xform. if (!xform.isRoot) { getXformData(xform); } MFnDagNode dagNode = new MFnDagNode(xform.mayaObjectPath); for (uint childIdx = 0; childIdx < dagNode.childCount; ++childIdx) { // If the child isn't a transform node, or it is a kManipulator3D (maya api bug), skip it. MObject childObj = dagNode.child(childIdx); if (!childObj.hasFn(MFn.Type.kTransform) || childObj.hasFn(MFn.Type.kManipulator3D)) { continue; } // Create a node for the child transform, parent it to this xform, and process the child's children. MFnDagNode childNode = new MFnDagNode(childObj); // Strip out nodes we don't care about. if (xformsToIgnore.Contains(childNode.fullPathName)) { continue; } MayaXform childXform = new MayaXform(); childXform.name = childNode.fullPathName; childNode.getPath(childXform.mayaObjectPath); childXform.parent = xform; xform.children.Add(childXform); processXform(childXform); } }
private void addSelectedButton_Click(object sender, EventArgs e) { if (currentInfo == null) { return; } MDagPath node; MObject component = new MObject(); MFnDagNode nodeFn = new MFnDagNode(); MSelectionList selected = new MSelectionList(); MGlobal.getActiveSelectionList(selected); for (uint index = 0; index < selected.length; index++) { node = selected.getDagPath(index, component); nodeFn.setObject(node); MGlobal.displayInfo($"{nodeFn.name} - {nodeFn.fullPathName} - {component.apiType}"); } }
/// <summary> /// /// </summary> /// <param name="mFnDagNode">DAG function set of the node below the transform</param> /// <param name="mDagPath">DAG path of the transform above the node</param> /// <returns></returns> private bool IsNodeExportable(MFnDagNode mFnDagNode, MDagPath mDagPath) { // TODO - Add custom property //if (gameNode.MaxNode.GetBoolProperty("babylonjs_noexport")) //{ // return false; //} if (_onlySelected && !selectedNodeFullPaths.Contains(mDagPath.fullPathName)) { return(false); } if (!_exportHiddenObjects && !mDagPath.isVisible) { return(false); } return(true); }
private void renameNodes(MObject transform, string baseName) { // Rename the transform to something we know no node will be using. dagMod.renameNode(transform, "polyPrimitiveCmdTemp"); // Rename the mesh to the same thing but with 'Shape' on the end. MFnDagNode dagFn = new MFnDagNode(transform); dagMod.renameNode(dagFn.child(0), "polyPrimitiveCmdTempShape"); // Now that they are in the 'something/somethingShape' format, any // changes we make to the name of the transform will automatically be // propagated to the shape as well. // // Maya will replace the '#' in the string below with a number which // ensures uniqueness. string transformName = baseName + "#"; dagMod.renameNode(transform, transformName); }
/// <summary> /// Return the type of the direct descendants of the node /// </summary> /// <param name="mDagPath"></param> /// <returns> Return Mesh, Camera, Light or Unknown</returns> private MFn.Type getApiTypeOfDirectDescendants(MDagPath mDagPath) { for (uint i = 0; i < mDagPath.childCount; i++) { MObject childObject = mDagPath.child(i); MFnDagNode nodeObject = new MFnDagNode(childObject); switch (childObject.apiType) { case MFn.Type.kMesh: if (IsMeshExportable(nodeObject, mDagPath)) { return(MFn.Type.kMesh); } break; case MFn.Type.kCamera: if (IsCameraExportable(nodeObject, mDagPath)) { return(MFn.Type.kCamera); } break; } // Lights api type are kPointLight, kSpotLight... // Easier to check if has generic light function set rather than check all cases if (mDagPath.hasFn(MFn.Type.kLight) && IsLightExportable(nodeObject, mDagPath)) { // Return generic kLight api type return(MFn.Type.kLight); } // Locators if (mDagPath.hasFn(MFn.Type.kLocator) && IsNodeExportable(nodeObject, mDagPath)) { return(MFn.Type.kLocator); } } return(MFn.Type.kUnknown); }
internal void MObjOnDeleted(object sender, MFnDagNode dagNode) { if (SelectedItems != null && SelectedItems.Count > 0) { if (SelectedItems.Count == 1) { base._hasBeenDeleted = true; } var uuidstr = dagNode.uuid().asString(); if (SelectedItems.ContainsKey(uuidstr)) { SelectedItems[uuidstr].Dispose(); SelectedItems.Remove(uuidstr); } OnNodeModified(true); } }
// Node added to model callback. #region UserCallbacks private static void userNodeRemovedCB(object sender, MNodeFunctionArgs arg) { MObject node = arg.node; if (!node.isNull) { MFnDagNode dagNode; try { dagNode = new MFnDagNode(node); string info = "DAG Model - Node removed: "; info += dagNode.name; MGlobal.displayInfo(info); } catch (System.Exception) { MGlobal.displayInfo("Error: failed to get dag node."); } } // remove the callback node.NodeRemovedFromModel -= userNodeRemovedCB; }
private void assignShadingGroup(MObject transform, string groupName) { // Get the name of the mesh node. // // We need to use an MFnDagNode rather than an MFnMesh because the mesh // is not fully realized at this point and would be rejected by MFnMesh. MFnDagNode dagFn = new MFnDagNode(transform); dagFn.setObject(dagFn.child(0)); string meshName = dagFn.name; // Use the DAG modifier to put the mesh into a shading group string cmd = "sets -e -fe "; cmd += groupName + " " + meshName; dagMod.commandToExecute(cmd); // Use the DAG modifier to select the new mesh. cmd = "select " + meshName; dagMod.commandToExecute(cmd); }
private bool IsNodeExportable(MFnDagNode mFnDagNode) { // TODO - Add custom property //if (gameNode.MaxNode.GetBoolProperty("babylonjs_noexport")) //{ // return false; //} // TODO - Fix fatal error: Attempting to save in C:/Users/Fabrice/AppData/Local/Temp/Fabrice.20171205.1613.ma //if (_onlySelected && !MGlobal.isSelected(mDagPath.node)) //{ // return false; //} // TODO - Fix fatal error: Attempting to save in C:/Users/Fabrice/AppData/Local/Temp/Fabrice.20171205.1613.ma //MDagPath mDagPath = mFnDagNode.dagPath; //if (!_exportHiddenObjects && !mDagPath.isVisible) //{ // return false; //} return(true); }
internal void MObjOnChanged(object sender, MFnDagNode dagNode) { if (!isUpdating) { isUpdating = true; var dag = new DMMesh(dagNode.dagPath, space); isFromUpdate = true; if (SelectedItems.ContainsKey(dag.dagName)) { SelectedItems[dag.dagName] = dag; dynamoMesh[dag.dagName] = AstFactory.BuildFunctionCall( dynamoElementFunc, new List <AssociativeNode> { AstFactory.BuildStringNode(dag.dagName), AstFactory.BuildStringNode(m_mSpace) }); mayaMesh[dag.dagName] = AstFactory.BuildFunctionCall( MayaElementFunc, new List <AssociativeNode> { AstFactory.BuildStringNode(dag.dagName), AstFactory.BuildStringNode(m_mSpace) }); } OnNodeModified(true); } }
// // Deal with nodes whose parenting is between referenced and non-referenced // nodes. // protected void writeRefNodeParenting(FileStream f) { uint numNodes = fParentingRequired.length; int i; for (i = 0; i < numNodes; i++) { MFnDagNode nodeFn = new MFnDagNode(fParentingRequired[i]); // // Find out if this node has any parents from referenced or // non-referenced files. // bool hasRefParents = false; bool hasNonRefParents = false; uint numParents = nodeFn.parentCount; uint p; for (p = 0; p < numParents; p++) { MObject parent = nodeFn.parent(p); MFnDagNode parentFn = new MFnDagNode(parent); if (parentFn.isFromReferencedFile) hasRefParents = true; else hasNonRefParents = true; if (hasRefParents && hasNonRefParents) break; } // // If this node is from a referenced file and it has parents which // are also from a referenced file, then it already has its first // parent and all others are added instances. // // Similarly if the node is not from a referenced file and has // parents which are also not from referenced files. // bool alreadyHasFirstParent = (nodeFn.isFromReferencedFile ? hasRefParents : hasNonRefParents); // // Now run through the parents again and output any parenting // which involves a non-referenced node, either as parent or child. // for (p = 0; p < numParents; p++) { MObject parent = nodeFn.parent(p); MFnDagNode parentFn = new MFnDagNode(parent); if (parentFn.isFromReferencedFile != nodeFn.isFromReferencedFile) { // // Get the first path to the parent. // MDagPath parentPath = new MDagPath(); MDagPath.getAPathTo(parentFn.objectProperty, parentPath); writeParent( f, parentPath, fParentingRequired[i], alreadyHasFirstParent ); // // If it didn't have its first parent before, it does now. // alreadyHasFirstParent = true; } } } }
// // Write out a 'createNode' command for a DAG node. // protected void writeCreateNode(FileStream f, MDagPath nodePath, MDagPath parentPath) { MObject node = new MObject(nodePath.node); MFnDagNode nodeFn = new MFnDagNode(node); string result = ""; // // Write out the 'createNode' command for this node. // result += ("createNode " + nodeFn.typeName); // // If the node is shared, then add a "-s/shared" flag to the command. // if (nodeFn.isShared) result += " -s"; result += (" -n \"" + nodeFn.name + "\""); // // If this is not a top-level node, then include its first parent in the // command. // if (parentPath.length > 0) result += (" -p \"" + parentPath.partialPathName + "\""); result += (";" + "\n"); writeString(f, result); }
// // Write out a "select" command. // protected void writeSelectNode(FileStream f, MObject node) { MFnDependencyNode nodeFn = new MFnDependencyNode(node); string nodeName; // // If the node has a unique name, then we can just go ahead and use // that. Otherwise we will have to use part of its DAG path to to // distinguish it from the others with the same name. // if (nodeFn.hasUniqueName) nodeName = nodeFn.name; else { // // Only DAG nodes are allowed to have duplicate names. // try { MFnDagNode dagNodeFn = new MFnDagNode(node); nodeName = dagNodeFn.partialPathName; } catch (Exception) { MGlobal.displayWarning( "Node '" + nodeFn.name + "' has a non-unique name but claimes to not be a DAG node.\n" + "Using non-unique name." ); nodeName = nodeFn.name; } } string result = ""; // // We use the "-ne/noExpand" flag so that if the node is a set, we // actually select the set itself, rather than its members. // result += "select -ne "; // // Default nodes get a colon slapped onto the start of their names. // if (nodeFn.isDefaultNode) result += ":"; result += (nodeName + ";\n"); writeString(f, result); }
//====================================================================== // // Check the parsed arguments and do/undo/redo the command as appropriate // void checkArgs(ref MArgDatabase argsDb) { //---------------------------------------- // -structure flag // fStructureFlag.parse(ref argsDb, flagStructure); if (fStructureFlag.isSet()) { if (!fStructureFlag.isArgValid()) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kInvalidString); throw new ArgumentException(errMsg, "argsDb"); } string structureName = fStructureFlag.arg(); try { fStructure = Structure.structureByName(structureName); } catch (System.Exception) { string msgFmt = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataStructureNotFound); throw new ArgumentException(String.Format(msgFmt, structureName), "argsDb"); } } else { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataNoStructureName); throw new ArgumentException(errMsg, "argsDb"); } //---------------------------------------- // -streamName flag // fStreamNameFlag.parse(ref argsDb, flagStreamName); if (fStreamNameFlag.isSet()) { if (!fStreamNameFlag.isArgValid()) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kInvalidString); throw new ArgumentException(errMsg, "argsDb"); } fStreamName = fStreamNameFlag.arg(); } else { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataNoStructureName); throw new ArgumentException(errMsg, "argsDb"); } //---------------------------------------- // -channelType flag // fChannelTypeFlag.parse(ref argsDb, flagChannelType); if (fChannelTypeFlag.isSet()) { if (!fChannelTypeFlag.isArgValid()) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kInvalidString); throw new ArgumentException(errMsg, "argsDb"); } fChannelType = fChannelTypeFlag.arg(); } else { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataNoStructureName); throw new ArgumentException(errMsg, "argsDb"); } //---------------------------------------- // (selection list) // // Commands need at least one node on which to operate so gather up // the list of nodes specified and/or selected. // // Empty out the list of nodes on which to operate so that it can be // populated from the selection or specified lists. fNodes.clear(); MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (uint i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { if (obj == MObject.kNullObj) { throw new ApplicationException("Error: objects.getDependNode() "); } fNodes.append(dagPath.node); } else { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError); String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]"); displayError(msg); throw new System.InvalidOperationException(msg); } } if (fNodes.length == 0) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); throw new ArgumentException(errMsg, "argsDb"); } }
private void linkXformsMeshes() { foreach( MayaXform xform in allXforms ) { // Convert to a DAG node to traverse children. MFnDagNode dagNode = new MFnDagNode(xform.mayaObjectPath); for( uint childIdx = 0; childIdx < dagNode.childCount; ++childIdx ) { MObject childObj = dagNode.child(childIdx); // If the child has a mesh, link it. if( childObj.hasFn(MFn.Type.kMesh) ) { xform.mesh = pathMeshMap[(new MFnMesh(childObj)).fullPathName]; break; } } } }
// // Write out all of the connections in the scene. // protected void writeConnections(FileStream f) { // // If the scene has broken any connections which were made in referenced // files, handle those first so that the attributes are free for any new // connections which may come along. // writeBrokenRefConnections(f); // // We're about to write out the scene's connections in three parts: DAG // nodes, non-DAG non-default nodes, then default nodes. // // It's really not necessary that we group them like this and would in // fact be more efficient to do them all in one MItDependencyNodes // traversal. However, this is the order in which the normal MayaAscii // translator does them, so this makes it easier to compare the output // of this translator to Maya's output. // // // Write out connections for the DAG nodes first. // MItDag dagIter = new MItDag(); dagIter.traverseUnderWorld(true); for (dagIter.next(); !dagIter.isDone; dagIter.next()) { MObject node = dagIter.item(); MFnDagNode dagNodeFn = new MFnDagNode(node); if (!dagNodeFn.isFlagSet(fConnectionFlag) && dagNodeFn.canBeWritten && !dagNodeFn.isDefaultNode) { writeNodeConnections(f, dagIter.item()); dagNodeFn.setFlag(fConnectionFlag, true); } } // // Now do the non-DAG, non-default nodes. // MItDependencyNodes nodeIter = new MItDependencyNodes(); for (; !nodeIter.isDone; nodeIter.next()) { MFnDependencyNode nodeFn = new MFnDependencyNode(nodeIter.item); if (!nodeFn.isFlagSet(fConnectionFlag) && nodeFn.canBeWritten && !nodeFn.isDefaultNode) { writeNodeConnections(f, nodeIter.item); nodeFn.setFlag(fConnectionFlag, true); } } // // And finish up with the default nodes. // uint numNodes = fDefaultNodes.length; int i; for (i = 0; i < numNodes; i++) { MFnDependencyNode nodeFn = new MFnDependencyNode(fDefaultNodes[i]); if (!nodeFn.isFlagSet(fConnectionFlag) && nodeFn.canBeWritten && nodeFn.isDefaultNode) { writeNodeConnections(f, fDefaultNodes[i]); nodeFn.setFlag(fConnectionFlag, true); } } }
protected internal virtual void OnDeleted(MFnDagNode dagNode) { Deleted?.Invoke(this, dagNode); }
// Decide if the dag is in the model. Dag paths and names // may not be setup if the dag has not been added to // the model. private static bool dagNotInModel(MDagPath dagPath) { MFnDagNode dagFn; bool inModel; try { dagFn = new MFnDagNode(dagPath); inModel = dagFn.inModel; } catch (System.Exception) { return false; } return (inModel == false); }
public void sendCurveToMaya(string node_name, Point3DCollection controlVertices, List<double> knots, int degree, MFnNurbsCurveForm form) { MFnDagNode dn = new MFnDagNode(getDagNode(node_name)); MPlug plCreate = dn.findPlug("create"); MPlug plDynamoCreate = new MPlug(); try { plDynamoCreate = dn.findPlug("dynamoCreate"); } catch { MFnTypedAttribute tAttr = new MFnTypedAttribute(); MObject ldaDynamoCreate = tAttr.create("dynamoCreate", "dc", MFnData.Type.kNurbsCurve, MObject.kNullObj); try { dn.addAttribute(ldaDynamoCreate, MFnDependencyNode.MAttrClass.kLocalDynamicAttr); plDynamoCreate = dn.findPlug(ldaDynamoCreate); MDagModifier dagm = new MDagModifier(); dagm.connect(plDynamoCreate, plCreate); dagm.doIt(); } catch { return; } } MFnNurbsCurveData ncd = new MFnNurbsCurveData(); MObject oOwner = ncd.create(); MFnNurbsCurve nc = new MFnNurbsCurve(); MPointArray p_aControlVertices = new MPointArray(); foreach (Point3D p in controlVertices) { p_aControlVertices.Add(new MPoint(p.X, p.Y, p.Z)); } MDoubleArray d_aKnots = new MDoubleArray(); for (int i = 1; i < knots.Count - 1; ++i ) { d_aKnots.Add(knots[i]); } nc.create(p_aControlVertices, d_aKnots, (uint)degree, (MFnNurbsCurve.Form)form, false, true, oOwner); plDynamoCreate.setMObject(oOwner); MGlobal.executeCommandOnIdle(String.Format("dgdirty {0}.create;", node_name)); }
private void buildLightNodes() { MItDependencyNodes it = new MItDependencyNodes(MFn.Type.kLight); while( !it.isDone ) { MObject mayaObj = it.thisNode; if( shouldPruneLight(mayaObj) ) { it.next(); continue; } // Create a new light and add it to the all lights list. MayaLight light = new MayaLight(); allLights.Add(light); light.id = allLights.Count - 1; // Get the dag node of the light for its name and parent. MFnDagNode dagNode = new MFnDagNode(mayaObj); dagNode.getPath(light.mayaObjectPath); light.name = dagNode.fullPathName; // First parent is the source transform node. light.sourceXform = pathXformMap[(new MFnDagNode(dagNode.parent(0))).fullPathName]; // Add the light to the dictionary to search by name. pathLightMap[light.name] = light; // // NOTE: Parent transforms of light sources in Maya can NOT be frozen, // so accessing them is guaranteed to not be frozen. // if( mayaObj.hasFn(MFn.Type.kAmbientLight) ) { MFnAmbientLight mayaLight = new MFnAmbientLight(mayaObj); light.type = MayaLight.Type.kAmbient; light.color = new Color(mayaLight.color.r, mayaLight.color.g, mayaLight.color.b, mayaLight.color.a); light.intensity = mayaLight.intensity; } else if( mayaObj.hasFn(MFn.Type.kDirectionalLight) ) { MFnDirectionalLight mayaLight = new MFnDirectionalLight(mayaObj); light.type = MayaLight.Type.kDirectional; light.color = new Color(mayaLight.color.r, mayaLight.color.g, mayaLight.color.b, mayaLight.color.a); light.intensity = mayaLight.intensity; } else if( mayaObj.hasFn(MFn.Type.kPointLight) ) { MFnPointLight mayaLight = new MFnPointLight(mayaObj); light.type = MayaLight.Type.kPoint; light.color = new Color(mayaLight.color.r, mayaLight.color.g, mayaLight.color.b, mayaLight.color.a); light.intensity = mayaLight.intensity; light.range = (float)mayaLight.centerOfIllumination; } else if( mayaObj.hasFn(MFn.Type.kSpotLight) ) { MFnSpotLight mayaLight = new MFnSpotLight(mayaObj); light.type = MayaLight.Type.kSpot; light.color = new Color(mayaLight.color.r, mayaLight.color.g, mayaLight.color.b, mayaLight.color.a); light.intensity = mayaLight.intensity; light.range = (float)mayaLight.centerOfIllumination; float mayaConeAngle = (float)(mayaLight.coneAngle * 0.5); light.coneInnerAngle = 57.29578f * mayaConeAngle; light.coneOuterAngle = 57.29578f * (mayaConeAngle + Math.Abs((float)mayaLight.penumbraAngle)); } it.next(); } }
private void buildMeshNodes() { MItDependencyNodes it = new MItDependencyNodes(MFn.Type.kMesh); while( !it.isDone ) { // Get the dag node of the mesh. MFnDagNode dagNode = new MFnDagNode(it.thisNode); // Create a new mesh. MayaMesh meshNode = new MayaMesh(); // Add the mesh to the all meshes list. allMeshes.Add(meshNode); // Configure the mesh node meshNode.name = dagNode.fullPathName; dagNode.getPath(meshNode.mayaObjectPath); meshNode.id = allMeshes.Count - 1; // The first parent of a mesh is the source transform, even with instances. meshNode.sourceXForm = pathXformMap[(new MFnDagNode(dagNode.parent(0))).fullPathName]; // Set the source Xform to know it's a source for an instance (its mesh). meshNode.sourceXForm.isSourceXform = true; // If the mesh has more than one parent, it has been instanced. We need to know this for computing local positions. meshNode.isInstanced = dagNode.isInstanced(); // Add the map to the dictionary to search by name. pathMeshMap[meshNode.name] = meshNode; it.next(); } }
//====================================================================== // // Do the metadata creation. The metadata will be randomly initialized // based on the channel type and the structure specified. For recognized // components the number of metadata elements will correspond to the count // of components in the selected mesh, otherwise a random number of metadata // elements between 1 and 100 will be created (at consecutive indices). // // The previously existing metadata is preserved for later undo. // override public void doIt(MArgList args) { MArgDatabase argsDb = new MArgDatabase(syntax, args); checkArgs(ref argsDb); clearResult(); uint numNodes = fNodes.length; for ( int i = 0; i < numNodes; ++i) { // fNodes[i] is the transform not the shape itself MFnDagNode dagNode = new MFnDagNode(fNodes[i]); MObject obj = dagNode.child(0); // obj is the shape, which is where we can add the meta data MFnDependencyNode node = new MFnDependencyNode(obj); Console.WriteLine( "METADATA for node " + dagNode.fullPathName ); Console.WriteLine( "=====================================================================" ); foreach( Channel chn in node.metadata) { Console.WriteLine("Channel: type = {0}, nbStreams = {1}", chn.nameProperty, chn.dataStreamCount); foreach (Stream strm in chn) { Console.WriteLine("Stream: name = {0}, nbElements = {1}", strm.name, strm.elementCount() ); Structure strct = strm.structure; Console.WriteLine("Structure: name = {0}, nbMembers = {1}", strct.name, strct.memberCount ); string[] memberNames = new string[strct.memberCount]; int memberID = -1; foreach( Member member in strct ) { ++memberID; Console.WriteLine("Structure member: name = {0}, type = {1}, array size = {2}", member.nameProperty, member.typeProperty.ToString(), member.lengthProperty ); memberNames[memberID] = member.nameProperty; } int k = -1; foreach (Handle handle in strm) { ++k; for (uint n = 0; n < strct.memberCount; ++n) { handle.setPositionByMemberIndex(n); Array data = handle.asType; if( data.Length < 1 ) throw new ApplicationException( "Handle data seems corrupted" ); string line = string.Format( "Handle #{0}, member = {1}, data = {2}", k, memberNames[n], data.GetValue(0).ToString() ); if( data.Length > 1 ) { for( int d = 1; d < data.Length; ++d ) { line = line + "," + data.GetValue(d).ToString(); } } Console.WriteLine( line ); } } } } } }
protected void writeDagNodes(FileStream f) { fParentingRequired.clear(); MItDag dagIter = new MItDag(); dagIter.traverseUnderWorld(true); MDagPath worldPath = new MDagPath(); dagIter.getPath(worldPath); // // We step over the world node before starting the loop, because it // doesn't get written out. // for (dagIter.next(); !dagIter.isDone; dagIter.next()) { MDagPath path = new MDagPath(); dagIter.getPath(path); // // If the node has already been written, then all of its descendants // must have been written, or at least checked, as well, so prune // this branch of the tree from the iteration. // MFnDagNode dagNodeFn = new MFnDagNode(path); if (dagNodeFn.isFlagSet(fCreateFlag)) { dagIter.prune(); continue; } // // If this is a default node, it will be written out later, so skip // it. // if (dagNodeFn.isDefaultNode) continue; // // If this node is not writable, and is not a shared node, then mark // it as having been written, and skip it. // if (!dagNodeFn.canBeWritten && !dagNodeFn.isShared) { dagNodeFn.setFlag(fCreateFlag, true); continue; } uint numParents = dagNodeFn.parentCount; if (dagNodeFn.isFromReferencedFile) { // // We don't issue 'creatNode' commands for nodes from referenced // files, but if the node has any parents which are not from // referenced files, other than the world, then make a note that // we'll need to issue extra 'parent' commands for it later on. // uint i; for (i = 0; i < numParents; i++) { MObject altParent = dagNodeFn.parent(i); MFnDagNode altParentFn = new MFnDagNode(altParent); if (!altParentFn.isFromReferencedFile && (altParentFn.objectProperty.notEqual(worldPath.node))) { fParentingRequired.append(path); break; } } } else { // // Find the node's parent. // MDagPath parentPath = new MDagPath(worldPath); if (path.length > 1) { // // Get the parent's path. // parentPath.assign(path); parentPath.pop(); // // If the parent is in the underworld, then find the closest // ancestor which is not. // if (parentPath.pathCount > 1) { // // The first segment of the path contains whatever // portion of the path exists in the world. So the closest // worldly ancestor is simply the one at the end of that // first path segment. // path.getPath(parentPath, 0); } } MFnDagNode parentNodeFn = new MFnDagNode(parentPath); if (parentNodeFn.isFromReferencedFile) { // // We prefer to parent to a non-referenced node. So if this // node has any other parents, which are not from referenced // files and have not already been processed, then we'll // skip this instance and wait for an instance through one // of those parents. // uint i; for (i = 0; i < numParents; i++) { if (dagNodeFn.parent(i).notEqual(parentNodeFn.objectProperty)) { MObject altParent = dagNodeFn.parent(i); MFnDagNode altParentFn = new MFnDagNode(altParent); if (!altParentFn.isFromReferencedFile && !altParentFn.isFlagSet(fCreateFlag)) { break; } } } if (i < numParents) continue; // // This node only has parents within referenced files, so // create it without a parent and note that we need to issue // 'parent' commands for it later on. // writeCreateNode(f, path, worldPath); fParentingRequired.append(path); } else { writeCreateNode(f, path, parentPath); // // Let's see if this node has any parents from referenced // files, or any parents other than this one which are not // from referenced files. // uint i; bool hasRefParents = false; bool hasOtherNonRefParents = false; for (i = 0; i < numParents; i++) { if (dagNodeFn.parent(i).notEqual(parentNodeFn.objectProperty)) { MObject altParent = dagNodeFn.parent(i); MFnDagNode altParentFn = new MFnDagNode(altParent); if (altParentFn.isFromReferencedFile) hasRefParents = true; else hasOtherNonRefParents = true; // // If we've already got positives for both tests, // then there's no need in continuing. // if (hasRefParents && hasOtherNonRefParents) break; } } // // If this node has parents from referenced files, then // make note that we will have to issue 'parent' commands // later on. // if (hasRefParents) fParentingRequired.append(path); // // If this node has parents other than this one which are // not from referenced files, then make note that the // parenting for the other instances still has to be done. // if (hasOtherNonRefParents) { fInstanceChildren.append(path); fInstanceParents.append(parentPath); } } // // Write out the node's 'addAttr', 'setAttr' and 'lockNode' // commands. // writeNodeAttrs(f, path.node, true); writeLockNode(f, path.node); } // // Mark the node as having been written. // dagNodeFn.setFlag(fCreateFlag, true); } // // Write out the parenting for instances. // writeInstances(f); }
public void ResetLights() { //<AmbientLight Color="White" /> //<DirectionalLight Color="White" Direction="-1,-1,-1" /> //<PointLight Color="White" ConstantAttenuation="1" LinearAttenuation="1" Position="0,0,0" QuadraticAttenuation="1" Range="0" /> //<SpotLight Color="White" ConstantAttenuation="1" Direction="-1,-1,-1" InnerConeAngle="10" LinearAttenuation="1" OuterConeAngle="10" Position="0,0,0" QuadraticAttenuation="1" Range="0" /> lights.Children.Clear () ; MItDag dagIterator =new MItDag (MItDag.TraversalType.kDepthFirst, MFn.Type.kLight) ; for ( ; !dagIterator.isDone ; dagIterator.next () ) { MDagPath lightPath =new MDagPath () ; dagIterator.getPath (lightPath) ; MFnLight light =new MFnLight (lightPath) ; bool isAmbient =light.lightAmbient ; MColor mcolor =light.color ; Color color =Color.FromScRgb (1.0f, mcolor.r, mcolor.g, mcolor.b) ; if ( isAmbient ) { AmbientLight ambient =new AmbientLight (color) ; lights.Children.Add (ambient) ; continue ; } MFloatVector lightDirection =light.lightDirection (0, MSpace.Space.kWorld) ; Vector3D direction =new Vector3D (lightDirection.x, lightDirection.y, lightDirection.z) ; bool isDiffuse =light.lightDiffuse ; try { MFnDirectionalLight dirLight =new MFnDirectionalLight (lightPath) ; DirectionalLight directional =new DirectionalLight (color, direction) ; lights.Children.Add (directional) ; continue ; } catch { } MObject transformNode =lightPath.transform ; MFnDagNode transform =new MFnDagNode (transformNode) ; MTransformationMatrix matrix =new MTransformationMatrix (transform.transformationMatrix) ; double [] threeDoubles =new double [3] ; int rOrder =0 ; //MTransformationMatrix.RotationOrder rOrder ; matrix.getRotation (threeDoubles, out rOrder, MSpace.Space.kWorld) ; matrix.getScale (threeDoubles, MSpace.Space.kWorld) ; MVector pos =matrix.getTranslation (MSpace.Space.kWorld) ; Point3D position =new Point3D (pos.x, pos.y, pos.z) ; try { MFnPointLight pointLight =new MFnPointLight (lightPath) ; PointLight point =new PointLight (color, position) ; //point.ConstantAttenuation =pointLight. ; // LinearAttenuation / QuadraticAttenuation //point.Range =pointLight.rayDepthLimit ; lights.Children.Add (point) ; continue ; } catch { } try { MFnSpotLight spotLight =new MFnSpotLight (lightPath) ; MAngle InnerConeAngle =new MAngle (spotLight.coneAngle) ; MAngle OuterConeAngle =new MAngle (spotLight.penumbraAngle) ; SpotLight spot =new SpotLight (color, position, direction, OuterConeAngle.asDegrees, InnerConeAngle.asDegrees) ; spot.ConstantAttenuation =spotLight.dropOff ; // LinearAttenuation / QuadraticAttenuation //spot.Range =spotLight.rayDepthLimit ; lights.Children.Add (spot) ; continue ; } catch { } } }
// // 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. // protected void writeInstances(FileStream f) { uint numInstancedNodes = fInstanceChildren.length; int i; for (i = 0; i < numInstancedNodes; i++) { MFnDagNode nodeFn = new MFnDagNode(fInstanceChildren[i]); uint numParents = nodeFn.parentCount; uint p; for (p = 0; p < numParents; p++) { // // We don't want to issue a 'parent' command for the node's // existing parent. // try { if (nodeFn.parent((uint)i).notEqual(fInstanceParents[i].node)) { MObject parent = nodeFn.parent((uint)i); MFnDagNode parentFn = new MFnDagNode(parent); if (!parentFn.isFromReferencedFile) { // // Get the first path to the parent node. // MDagPath parentPath = new MDagPath(); MDagPath.getAPathTo(parentFn.objectProperty, parentPath); writeParent(f, parentPath, fInstanceChildren[i], true); } } } catch (Exception) { continue; } } } // // We don't need this any more, so free up the space. // fInstanceChildren.clear(); fInstanceParents.clear(); }
private void doScan(MItDag.TraversalType traversalType, MFn.Type filter, bool quiet) { MItDag dagIterator = new MItDag(traversalType, filter); // Scan the entire DAG and output the name and depth of each node if (traversalType == MItDag.TraversalType.kBreadthFirst) if (!quiet) MGlobal.displayInfo(Environment.NewLine + "Starting Breadth First scan of the Dag"); else if (!quiet) MGlobal.displayInfo(Environment.NewLine + "Starting Depth First scan of the Dag"); switch (filter) { case MFn.Type.kCamera: if (!quiet) MGlobal.displayInfo( ": Filtering for Cameras\n"); break; case MFn.Type.kLight: if (!quiet) MGlobal.displayInfo(": Filtering for Lights\n"); break; case MFn.Type.kNurbsSurface: if (!quiet) MGlobal.displayInfo(": Filtering for Nurbs Surfaces\n"); break; default: MGlobal.displayInfo(Environment.NewLine); break; } int objectCount = 0; for ( ; !dagIterator.isDone; dagIterator.next() ) { MDagPath dagPath = new MDagPath(); try { dagIterator.getPath(dagPath); } catch (System.Exception ) { continue; } MFnDagNode dagNode = null; try { dagNode = new MFnDagNode(dagPath); } catch (System.Exception ) { continue; } if (!quiet) MGlobal.displayInfo(dagNode.name + ": " + dagNode.typeName + Environment.NewLine); if (!quiet) MGlobal.displayInfo( " dagPath: " + dagPath.fullPathName + Environment.NewLine); objectCount += 1; if (dagPath.hasFn(MFn.Type.kCamera)) { MFnCamera camera = null; try { camera = new MFnCamera(dagPath); } catch (System.Exception) { continue; } // Get the translation/rotation/scale data // printTransformData(dagPath, quiet); // Extract some interesting Camera data // if (!quiet) { MGlobal.displayInfo(" eyePoint: " + MPointToString(camera.eyePoint(MSpace.Space.kWorld)) + Environment.NewLine); MGlobal.displayInfo(" upDirection: " + MVectorToString( camera.upDirection(MSpace.Space.kWorld)) + Environment.NewLine); MGlobal.displayInfo(" viewDirection: " + MVectorToString( camera.viewDirection(MSpace.Space.kWorld)) + Environment.NewLine); MGlobal.displayInfo(" aspectRatio: " + Convert.ToString( camera.aspectRatio ) + Environment.NewLine); MGlobal.displayInfo(" horizontalFilmAperture: " + Convert.ToString(camera.horizontalFilmAperture ) + Environment.NewLine); MGlobal.displayInfo(" verticalFilmAperture: " + Convert.ToString(camera.verticalFilmAperture ) + Environment.NewLine); } } else if (dagPath.hasFn(MFn.Type.kLight)) { MFnLight light = null; try { light = new MFnLight(dagPath); } catch (System.Exception) { continue; } // Get the translation/rotation/scale data // printTransformData(dagPath, quiet); // Extract some interesting Light data // MColor color = light.color; if (!quiet) { MGlobal.displayInfo(string.Format(" color: [%f, %f, %f]\n", color.r, color.g, color.b)); } color = light.shadowColor; if (!quiet) { MGlobal.displayInfo(string.Format(" shadowColor: [%f, %f, %f]\n", color.r, color.g, color.b)); MGlobal.displayInfo(" intensity: "+Convert.ToString(light.intensity) + Environment.NewLine); } } else if (dagPath.hasFn(MFn.Type.kNurbsSurface)) { MFnNurbsSurface surface= null; try { surface = new MFnNurbsSurface(dagPath); } catch (System.Exception ) { continue; } // Get the translation/rotation/scale data // printTransformData(dagPath, quiet); // Extract some interesting Surface data // if (!quiet) { MGlobal.displayInfo(string.Format(" numCVs: %d * %s", surface.numCVsInU, surface.numCVsInV) + Environment.NewLine); MGlobal.displayInfo(string.Format(" numKnots: %d * %s\n", surface.numKnotsInU, surface.numKnotsInV) + Environment.NewLine); MGlobal.displayInfo(string.Format(" numSpans: %d * %s\n", surface.numSpansInU, surface.numSpansInV) + Environment.NewLine); } } else { // Get the translation/rotation/scale data // printTransformData(dagPath, quiet); } } setResult(objectCount); }
// The implementation here is a bit different from its counterpart C++ sample because // .NET SDK decides not to support the obsolete C++ API: // // bool connectTargetAttribute (void *opaqueTarget, int index, MObject &constraintAttr); // protected override bool connectTarget( MDagPath targetPath, int index ) { try { MObject targetObject = new MObject(targetPath.node); MFnDagNode targetDagNode = new MFnDagNode(targetObject); connectTargetAttribute(targetPath, index, targetDagNode.attribute("worldMesh"), GeometrySurfaceConstraint.targetGeometry); } catch (Exception) { MGlobal.displayError("Failed to connect target."); return false; } return true; }
void printTransformData(MDagPath dagPath, bool quiet) { MObject transformNode = null; try { transformNode = dagPath.transform; } catch (System.Exception) { // This node has no transform - i.e., it's the world node // return; } MFnDagNode transform = null; try { transform = new MFnDagNode(transformNode); } catch (System.Exception ) { return; } MTransformationMatrix matrix = new MTransformationMatrix(transform.transformationMatrix); if (!quiet) { MGlobal.displayInfo(" translation: " + MVectorToString(matrix.translation(MSpace.Space.kWorld)) + Environment.NewLine); } double[] threeDoubles = new double[3]; int rOrder = 0; matrix.getRotation (threeDoubles, out rOrder, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" rotation: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } matrix.getScale (threeDoubles, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" scale: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } }
//====================================================================== // // Do the metadata creation. The metadata will be randomly initialized // based on the channel type and the structure specified. For recognized // components the number of metadata elements will correspond to the count // of components in the selected mesh, otherwise a random number of metadata // elements between 1 and 100 will be created (at consecutive indices). // // The previously existing metadata is preserved for later undo. // override public void doIt(MArgList args) { MArgDatabase argsDb = new MArgDatabase(syntax, args); checkArgs(ref argsDb); clearResult(); uint numNodes = fNodes.length; int i; for (i = 0; i < numNodes; ++i) { // fNodes[i] is the transform not the shape itself MFnDagNode dagNode = new MFnDagNode(fNodes[i]); MObject obj = dagNode.child(0); // obj is the shape, which is where we can add the meta data MFnDependencyNode node = new MFnDependencyNode(obj); // Get the current metadata (empty if none yet) Associations newMetadata = new Associations(node.metadata); Channel newChannel = newMetadata.channel(fChannelType); // Check to see if the requested stream name already exists Stream oldStream = newChannel.dataStream(fStreamName); if (oldStream != null) { string fmt = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataHasStream); string msg = String.Format(fmt, fStreamName); MGlobal.displayError( msg ); continue; } Stream newStream = new Stream(fStructure, fStreamName); string strmName = newStream.name; int indexCount = 0; MFnMesh mesh = null; Random rndIndexCount = new Random(); // Treat the channel type initializations different for meshes if (obj.hasFn(MFn.Type.kMesh)) { mesh = new MFnMesh(obj); // Get mesh-specific channel type parameters if (fChannelType == "face") { indexCount = mesh.numPolygons; } else if (fChannelType == "edge") { indexCount = mesh.numEdges; } else if (fChannelType == "vertex") { indexCount = mesh.numVertices; } else if (fChannelType == "vertexFace") { indexCount = mesh.numFaceVertices; } else { // Set a random number between 1 to 100 indexCount = rndIndexCount.Next(1, 100); } } else { // Create generic channel type information indexCount = rndIndexCount.Next(1, 100); } // Fill specified stream ranges with random data int structureMemberCount = fStructure.memberCount; uint m,n,d; Random rnd = new Random(); for (m = 0; m < indexCount; ++m) { // Walk each structure member and fill with random data // tailored to the member data type. Handle handle = new Handle(fStructure); for (n = 0; n < structureMemberCount; ++n) { handle.setPositionByMemberIndex(n); switch (handle.dataType) { case Member.eDataType.kBoolean: { bool[] data = new bool[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { int randomInt = rnd.Next(0, 2); bool randomBool = randomInt == 1 ? true : false; data[d] = randomBool; } handle.asBooleanArray = data; break; } case Member.eDataType.kDouble: { double[] data = new double[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { // Set a random number between -2000000000.0.0 and 2000000000.0.0 data[d] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; } handle.asDoubleArray = data; break; } case Member.eDataType.kDoubleMatrix4x4: { double[] data = new double[handle.dataLength * 16]; for (d = 0; d < handle.dataLength; ++d) { data[d*16+0] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+1] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+2] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+3] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+4] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+5] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+6] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+7] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+8] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+9] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+10] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+11] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+12] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+13] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+14] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; data[d*16+15] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ; } handle.asDoubleMatrix4x4 = data; break; } case Member.eDataType.kFloat: { float[] data = new float[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { // Set a random number between -2000000.0 and 2000000.0 data[d] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; } handle.asFloatArray = data; break; } case Member.eDataType.kFloatMatrix4x4: { float[] data = new float[handle.dataLength * 16]; for (d = 0; d < handle.dataLength; ++d) { // Set a random number between -2000000.0 and 2000000.0 data[d*16+0] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+1] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+2] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+3] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+4] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+5] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+6] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+7] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+8] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+9] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+10] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+11] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+12] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+13] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+14] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; data[d*16+15] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ; } handle.asFloatMatrix4x4 = data; break; } case Member.eDataType.kInt8: { sbyte[] data = new sbyte[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { data[d] = (sbyte)rnd.Next(SByte.MinValue, SByte.MaxValue+1); } handle.asInt8Array = data; break; } case Member.eDataType.kInt16: { short[] data = new short[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { data[d] = (short)rnd.Next(Int16.MinValue, Int16.MaxValue+1); } handle.asInt16Array = data; break; } case Member.eDataType.kInt32: { int[] data = new int[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { // rnd.Next returns a number between [arg1,arg2[ // but unfortunately I can't pass Int32.MaxValue+1 here.... data[d] = rnd.Next(Int32.MinValue, Int32.MaxValue); } handle.asInt32Array = data; break; } case Member.eDataType.kInt64: { long[] data = new long[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { // rnd.Next() gives a number between [0,Int32 data[d] = (long)rnd.Next(Int32.MinValue, Int32.MaxValue); if( data[d] >= 0 ) data[d] *= Int64.MaxValue / Int32.MaxValue; else data[d] *= Int64.MinValue / Int32.MinValue; } handle.asInt64Array = data; break; } case Member.eDataType.kUInt8: { byte[] data = new byte[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { data[d] = (byte)rnd.Next(0, Byte.MaxValue + 1); } handle.asUInt8Array = data; break; } case Member.eDataType.kUInt16: { ushort[] data = new ushort[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { data[d] = (ushort)rnd.Next(0, UInt16.MaxValue + 1); } handle.asUInt16Array = data; break; } case Member.eDataType.kUInt32: { uint[] data = new uint[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { data[d] = (uint)rnd.Next(); } handle.asUInt32Array = data; break; } case Member.eDataType.kUInt64: { ulong[] data = new ulong[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { data[d] = ((ulong)rnd.Next()) * UInt64.MaxValue / UInt32.MaxValue; } handle.asUInt64Array = data; break; } case Member.eDataType.kString: { string[] randomStrings = new string[] { "banana", "tomatoe", "apple", "pineapple", "apricot", "pepper", "olive", "grapefruit" }; string[] data = new string[handle.dataLength]; for (d = 0; d < handle.dataLength; ++d) { int index = rnd.Next( randomStrings.Length ); data[d] = randomStrings[index]; } handle.asStringArray = data; break; } default: { Debug.Assert(false, "This should never happen"); break; } } } newStream.setElement(new Index(m), handle); } newChannel.setDataStream(newStream); newMetadata.setChannel(newChannel); // Note: the following will not work if "obj" is a shape constructed by a source object // You need to delete the history of the shape before calling this... fDGModifier.setMetadata(obj, newMetadata); fDGModifier.doIt(); // Set the result to the number of actual metadata values set as a // triple value: // (# nodes, # metadata elements, # members per element) // MIntArray theResult = new MIntArray(); theResult.append( (int) fNodes.length ); theResult.append( (int) indexCount ); theResult.append( (int) structureMemberCount ); setResult( theResult ); } }
private void processXform( MayaXform xform ) { // Add the current Xform to the list of all xforms. allXforms.Add(xform); // Set the Xform's id. xform.id = allXforms.Count - 1; // Add the current Xform to the map based on its path. pathXformMap[xform.name] = xform; // Build data for this xform. if( !xform.isRoot ) { getXformData(xform); } MFnDagNode dagNode = new MFnDagNode(xform.mayaObjectPath); for( uint childIdx = 0; childIdx < dagNode.childCount; ++childIdx ) { // If the child isn't a transform node, or it is a kManipulator3D (maya api bug), skip it. MObject childObj = dagNode.child(childIdx); if( !childObj.hasFn(MFn.Type.kTransform) || childObj.hasFn(MFn.Type.kManipulator3D) ) { continue; } // Create a node for the child transform, parent it to this xform, and process the child's children. MFnDagNode childNode = new MFnDagNode(childObj); // Strip out nodes we don't care about. if( xformsToIgnore.Contains(childNode.fullPathName) ) { continue; } MayaXform childXform = new MayaXform(); childXform.name = childNode.fullPathName; childNode.getPath(childXform.mayaObjectPath); childXform.parent = xform; xform.children.Add(childXform); processXform(childXform); } }
/// <summary> /// /// </summary> /// <param name="mFnDagNode">DAG function set of the node (mesh) below the transform</param> /// <param name="mDagPath">DAG path of the transform above the node</param> /// <returns></returns> private bool IsMeshExportable(MFnDagNode mFnDagNode, MDagPath mDagPath) { return(IsNodeExportable(mFnDagNode, mDagPath)); }
// // Description: // Overloaded function from MPxDragAndDropBehavior // this method will handle the connection between the slopeShaderNodeCSharp and the shader it is // assigned to as well as any meshes that it is assigned to. // public override void connectNodeToNode(MObject sourceNode, MObject destinationNode, bool force) { MFnDependencyNode src = new MFnDependencyNode(sourceNode); //if we are dragging from a lambert //we want to check what we are dragging //onto. if(sourceNode.hasFn(MFn.Type.kLambert)) { //MObject shaderNode; MPlugArray connections = new MPlugArray(); MObjectArray shaderNodes = new MObjectArray(); shaderNodes.clear(); //if the source node was a lambert //than we will check the downstream connections to see //if a slope shader is assigned to it. // src.getConnections(connections); int i; for(i = 0; i < connections.length; i++) { //check the incoming connections to this plug // MPlugArray connectedPlugs = new MPlugArray(); connections[i].connectedTo(connectedPlugs, true, false); for(uint j = 0; j < connectedPlugs.length; j++) { //if the incoming node is a slope shader than //append the node to the shaderNodes array // MObject currentnode = connectedPlugs[i].node; if (new MFnDependencyNode(currentnode).typeName == "slopeShaderNodeCSharp") { shaderNodes.append(currentnode); } } } //if we found a shading node //than check the destination node //type to see if it is a mesh // if(shaderNodes.length > 0) { MFnDependencyNode dest = new MFnDependencyNode(destinationNode); if(destinationNode.hasFn(MFn.Type.kMesh)) { //if the node is a mesh than for each slopeShaderNodeCSharp //connect the worldMesh attribute to the dirtyShaderPlug //attribute to force an evaluation of the node when the mesh //changes // for(i = 0; i < shaderNodes.length; i++) { MPlug srcPlug = dest.findPlug("worldMesh"); MPlug destPlug = new MFnDependencyNode(shaderNodes[i]).findPlug("dirtyShaderPlug"); if(!srcPlug.isNull && !destPlug.isNull) { string cmd = "connectAttr -na "; cmd += srcPlug.name + " "; cmd += destPlug.name; try { // in slopeShaderBehavior.cpp, this may excute failed but continue on the following code, so we catch it. MGlobal.executeCommand(cmd); } catch (System.Exception) { MGlobal.displayError("ExcuteCommand (" + cmd + ") failed."); } } } //get the shading engine so we can assign the shader //to the mesh after doing the connection // MObject shadingEngine = findShadingEngine(sourceNode); //if there is a valid shading engine than make //the connection // if(!shadingEngine.isNull) { string cmd = "sets -edit -forceElement "; cmd += new MFnDependencyNode(shadingEngine).name + " "; cmd += new MFnDagNode(destinationNode).partialPathName; MGlobal.executeCommand(cmd); } } } } else if (src.typeName == "slopeShaderNodeCSharp") //if we are dragging from a slope shader //than we want to see what we are dragging onto // { if(destinationNode.hasFn(MFn.Type.kMesh)) { //if the user is dragging onto a mesh //than make the connection from the worldMesh //to the dirtyShader plug on the slopeShaderNodeCSharp // MFnDependencyNode dest = new MFnDependencyNode(destinationNode); MPlug srcPlug = dest.findPlug("worldMesh"); MPlug destPlug = src.findPlug("dirtyShaderPlug"); if(!srcPlug.isNull && !destPlug.isNull) { string cmd = "connectAttr -na "; cmd += srcPlug.name + " "; cmd += destPlug.name; MGlobal.executeCommand(cmd); } } } return; }
protected internal virtual void OnChanged(MFnDagNode dagNode) { Changed?.Invoke(this, dagNode); }
protected internal virtual void OnRenamed(MFnDagNode dagNode) { Renamed?.Invoke(this, dagNode); }