// The compute() method does the actual work of the node using the inputs // of the node to generate its output. // // Compute takes two parameters: plug and data. // - Plug is the the data value that needs to be recomputed // - Data provides handles to all of the nodes attributes, only these // handles should be used when performing computations. // public override bool compute(MPlug plug, MDataBlock dataBlock) { MObject thisNode = thisMObject(); MFnDependencyNode fnThisNode = new MFnDependencyNode(thisNode); MGlobal.displayInfo("affects::compute(), plug being computed is \"" + plug.name + "\""); if (plug.partialName() == "B") { // Plug "B" is being computed. Assign it the value on plug "A" // if "A" exists. // MPlug pA = fnThisNode.findPlug("A"); MGlobal.displayInfo("\t\t... found dynamic attribute \"A\", copying its value to \"B\""); MDataHandle inputData = dataBlock.inputValue(pA); int value = inputData.asInt; MDataHandle outputHandle = dataBlock.outputValue( plug ); outputHandle.set(value); dataBlock.setClean(plug); } else { return false; } return true; }
// // Description: // Overloaded function from MPxDragAndDropBehavior // this method will assign the correct output from the slope shader // onto the given attribute. // public override void connectNodeToAttr(MObject sourceNode, MPlug destinationPlug, bool force) { MFnDependencyNode src = new MFnDependencyNode(sourceNode); //if we are dragging from a slopeShaderNodeCSharp //to a shader than connect the outColor //plug to the plug being passed in // if(destinationPlug.node.hasFn(MFn.Type.kLambert)) { if (src.typeName == "slopeShaderNodeCSharp") { MPlug srcPlug = src.findPlug("outColor"); if(!srcPlug.isNull && !destinationPlug.isNull) { string cmd = "connectAttr "; cmd += srcPlug.name + " "; cmd += destinationPlug.name; MGlobal.executeCommand(cmd); } } } else { //in all of the other cases we do not need the plug just the node //that it is on // MObject destinationNode = destinationPlug.node; connectNodeToNode(sourceNode, destinationNode, force); } }
public override void writer(MFileObject file, string optionsString, MPxFileTranslator.FileAccessMode mode) { string fullName = file.fullName; StreamWriter sWriter = new StreamWriter(fullName); sWriter.Write("# Simple text file of custom node information" + Environment.NewLine); MItDependencyNodes iterator = new MItDependencyNodes(); while (!iterator.isDone) { MObject obj = iterator.thisNode; try { MFnDependencyNode dnFn = new MFnDependencyNode(obj); MPxNode userNode = dnFn.userNode; if (userNode != null) sWriter.Write("# custom node: " + dnFn.name + Environment.NewLine); } catch (System.Exception) { } iterator.next(); } sWriter.Close(); return; }
private bool isAiStandardSurface(MFnDependencyNode materialDependencyNode) { // TODO - Find a better way to identify material type return(materialDependencyNode.hasAttribute("baseColor") && materialDependencyNode.hasAttribute("metalness") && materialDependencyNode.hasAttribute("normalCamera") && materialDependencyNode.hasAttribute("specularRoughness") && materialDependencyNode.hasAttribute("emissionColor")); }
public override void connectToDependNode(MObject node) { // Find the rotate and rotatePivot plugs on the node. These plugs will // be attached either directly or indirectly to the manip values on the // rotate manip. // MFnDependencyNode nodeFn = new MFnDependencyNode(node); MPlug rPlug = nodeFn.findPlug("rotate"); MPlug rcPlug = nodeFn.findPlug("rotatePivot"); // If the translate pivot exists, it will be used to move the state manip // to a convenient location. // MPlug tPlug = nodeFn.findPlug("translate"); // To avoid having the object jump back to the default rotation when the // manipulator is first used, extract the existing rotation from the node // and set it as the initial rotation on the manipulator. // MEulerRotation existingRotation = new MEulerRotation(vectorPlugValue(rPlug)); MVector existingTranslation = new MVector(vectorPlugValue(tPlug)); // // The following code configures default settings for the rotate // manipulator. // MFnRotateManip rotateManip = new MFnRotateManip(fRotateManip); rotateManip.setInitialRotation(existingRotation); rotateManip.setRotateMode(MFnRotateManip.RotateMode.kObjectSpace); rotateManip.displayWithNode(node); // Add a callback function to be called when the rotation value changes // //rotatePlugIndex = addManipToPlugConversionCallback( rPlug, (manipToPlugConversionCallback)&exampleRotateManip::rotationChangedCallback ); ManipToPlugConverion[rPlug] = rotationChangedCallback; // get the index of plug rotatePlugIndex = this[rPlug]; // Create a direct (1-1) connection to the rotation center plug // rotateManip.connectToRotationCenterPlug(rcPlug); // Place the state manip at a distance of 2.0 units away from the object // along the X-axis. // MFnStateManip stateManip = new MFnStateManip(fStateManip); MVector delta = new MVector(2, 0, 0); stateManip.setTranslation(existingTranslation + delta, MSpace.Space.kTransform); finishAddingManips(); base.connectToDependNode(node); }
public static bool ProjectPlug(MPlug from, MPlug to, float fromMin, float fromMax, float toMin, float toMax) { MFnDependencyNode remapValueNode = BasicFunc.CreateRemapValueNode(fromMin, fromMax, toMin, toMax); MDGModifier dGModifier = new MDGModifier(); dGModifier.connect(from, remapValueNode.findPlug(ConstantValue.plugName_remapValueInput)); dGModifier.connect(remapValueNode.findPlug(ConstantValue.plugName_remapValueOutput), to); dGModifier.doIt(); return(true); }
public override void connectToDependNode(MObject node) { // Find the rotate and rotatePivot plugs on the node. These plugs will // be attached either directly or indirectly to the manip values on the // rotate manip. // MFnDependencyNode nodeFn = new MFnDependencyNode(node); MPlug rPlug = nodeFn.findPlug("rotate"); MPlug rcPlug = nodeFn.findPlug("rotatePivot"); // If the translate pivot exists, it will be used to move the state manip // to a convenient location. // MPlug tPlug = nodeFn.findPlug("translate"); // To avoid having the object jump back to the default rotation when the // manipulator is first used, extract the existing rotation from the node // and set it as the initial rotation on the manipulator. // MEulerRotation existingRotation = new MEulerRotation(vectorPlugValue(rPlug)); MVector existingTranslation = new MVector(vectorPlugValue(tPlug)); // // The following code configures default settings for the rotate // manipulator. // MFnRotateManip rotateManip = new MFnRotateManip(fRotateManip); rotateManip.setInitialRotation(existingRotation); rotateManip.setRotateMode(MFnRotateManip.RotateMode.kObjectSpace); rotateManip.displayWithNode(node); // Add a callback function to be called when the rotation value changes // //rotatePlugIndex = addManipToPlugConversionCallback( rPlug, (manipToPlugConversionCallback)&exampleRotateManip::rotationChangedCallback ); ManipToPlugConverion[rPlug] = rotationChangedCallback; // get the index of plug rotatePlugIndex = this[rPlug]; // Create a direct (1-1) connection to the rotation center plug // rotateManip.connectToRotationCenterPlug(rcPlug); // Place the state manip at a distance of 2.0 units away from the object // along the X-axis. // MFnStateManip stateManip = new MFnStateManip(fStateManip); MVector delta = new MVector(2, 0, 0); stateManip.setTranslation(existingTranslation + delta, MSpace.Space.kTransform); finishAddingManips(); base.connectToDependNode(node); }
public static MFnDependencyNode GetPlace2dTextureForTex(MObject imageObject, bool createIfNotExist = true) { if (imageObject == null) { Debug.Log("image object null"); return(null); } MFnDependencyNode imageNode = new MFnDependencyNode(imageObject); return(GetPlace2dTextureForTex(imageNode, createIfNotExist)); }
private void ExportCommonBabylonAttributes(MFnDependencyNode babylonAttributesDependencyNode, BabylonPBRMetallicRoughnessMaterial babylonMaterial) { ExportCommonBabylonAttributes0(babylonAttributesDependencyNode, babylonMaterial); if (babylonAttributesDependencyNode.hasAttribute("babylonTransparencyMode")) { int v = babylonAttributesDependencyNode.findPlug("babylonTransparencyMode").asInt(); RaiseVerbose($"babylonTransparencyMode={v}", 3); babylonMaterial.transparencyMode = v; } }
private BabylonTexture _ExportTexture(MFnDependencyNode materialDependencyNode, string plugName, BabylonScene babylonScene, bool allowCube = false, bool forceAlpha = false, bool forceSpherical = false, float amount = 1.0f) { if (!materialDependencyNode.hasAttribute(plugName)) { RaiseError("Unknown attribute " + materialDependencyNode.name + "." + plugName, logRankTexture); return(null); } MFnDependencyNode textureDependencyNode = getTextureDependencyNode(materialDependencyNode, plugName); return(_ExportTexture(textureDependencyNode, babylonScene, allowCube, forceAlpha, forceSpherical, amount)); }
private void RenameHierachy(object sender, RoutedEventArgs e) { BasicFunc.IterateSelectedDags((dag) => { List <MDagPath> dags = BasicFunc.GetHierachyAll(dag); foreach (MDagPath d in dags) { MFnDependencyNode node = new MFnDependencyNode(d.node); node.setName(GetNewName(node.name)); } }); }
private BabylonTexture _ExportTexture(MFnDependencyNode materialDependencyNode, string plugName, BabylonScene babylonScene, bool allowCube = false, bool forceAlpha = false, bool updateCoordinatesMode = false, float amount = 1.0f) { if (!materialDependencyNode.hasAttribute(plugName)) { RaiseError("Unknown attribute " + materialDependencyNode.name + "." + plugName, logRankTexture); return(null); } List <MFnDependencyNode> textureModifiers = new List <MFnDependencyNode>(); MFnDependencyNode textureDependencyNode = getTextureDependencyNode(materialDependencyNode, plugName, textureModifiers); return(_ExportTexture(textureDependencyNode, babylonScene, textureModifiers, allowCube, forceAlpha, updateCoordinatesMode, amount)); }
private MFnDependencyNode getTextureDependencyNode(MFnDependencyNode materialDependencyNode, string plugName, List <MFnDependencyNode> textureModifiers = null) { MPlug mPlug = materialDependencyNode.findPlug(plugName); if (mPlug == null || mPlug.isNull || !mPlug.isConnected) { return(null); } MObject sourceObject = mPlug.source.node; MFnDependencyNode textureDependencyNode = new MFnDependencyNode(sourceObject); RaiseMessage(materialDependencyNode.name + "." + plugName, logRankTexture); // Bump texture uses an intermediate node if (sourceObject.hasFn(MFn.Type.kBump)) { Print(textureDependencyNode, logRankTexture, "Print bump node"); logRankTexture++; if (textureModifiers != null) { textureModifiers.Add(textureDependencyNode); } return(getTextureDependencyNode(textureDependencyNode, "bumpValue", textureModifiers)); } // If a reverse node is used as an intermediate node if (sourceObject.hasFn(MFn.Type.kReverse)) { Print(textureDependencyNode, logRankTexture, "Print reverse node"); // TODO - reverse? logRankTexture++; if (textureModifiers != null) { textureModifiers.Add(textureDependencyNode); } return(getTextureDependencyNode(textureDependencyNode, "input", textureModifiers)); } // If a projection node is used as an intermediate node if (sourceObject.hasFn(MFn.Type.kProjection)) { Print(textureDependencyNode, logRankTexture, "Print projection node"); logRankTexture++; if (textureModifiers != null) { textureModifiers.Add(textureDependencyNode); } return(getTextureDependencyNode(textureDependencyNode, "image", textureModifiers)); } return(textureDependencyNode); }
public static string RenameTexFile(MFnDependencyNode imageNode, string newPartialName, string newFolder = null, bool relinkImgNode = false, bool deleteOrigin = false, bool overwrite = false) { MPlug plug_fileTexPath = imageNode.findPlug(ConstantValue.plugName_fileTexPath); string originFullPath = plug_fileTexPath.asString(); string newFullPath = BasicFunc.RenameFile(originFullPath, newPartialName, newFolder, deleteOrigin, overwrite); if (relinkImgNode) { plug_fileTexPath.setString(newFullPath); } return(newFullPath); }
public static MFnDependencyNode CreateRemapValueNode(float inputMin, float inputMax, float outputMin, float outputMax) { MFnDependencyNode dependencyNode = new MFnDependencyNode(); dependencyNode.create("remapValue"); //Debug.Log("created node:" + (*dependencyNode).absoluteName()); dependencyNode.findPlug("inputMin").setFloat(inputMin); dependencyNode.findPlug("inputMax").setFloat(inputMax); dependencyNode.findPlug("outputMin").setFloat(outputMin); dependencyNode.findPlug("outputMax").setFloat(outputMax); return(dependencyNode); }
/// <summary> /// Extract a material and its linked texture, if any. /// </summary> private static void ExtractMaterial(MayaM2Mesh mesh, MObject material) { var fnShader = new MFnLambertShader(material); // Get lambert out of the shader var strName = fnShader.name; MGlobal.displayInfo("Detected material : " + strName + " of type " + material.apiTypeStr); //TODO use this type // ReSharper disable once UnusedVariable var clrDiffuse = fnShader.color; // ReSharper disable once UnusedVariable var clrAmbient = fnShader.ambientColor; if (material.hasFn(MFn.Type.kReflect)) { var fnReflectShader = new MFnReflectShader(material); // ReSharper disable once UnusedVariable var clrSpec = fnReflectShader.specularColor; } // Look for textures at the color plug var colorPlug = fnShader.findPlug("color"); var fileTextureIter = new MItDependencyGraph(colorPlug.node, MFn.Type.kFileTexture, MItDependencyGraph.Direction.kUpstream, MItDependencyGraph.Traversal.kDepthFirst, MItDependencyGraph.Level.kNodeLevel); while (!fileTextureIter.isDone) { //TODO hardcoded textures var nodeFn = new MFnDependencyNode(fileTextureIter.thisNode()); var fileNamePlug = nodeFn.findPlug("fileTextureName"); string textureFileName; fileNamePlug.getValue(out textureFileName); MGlobal.displayInfo("\t Texture found : " + textureFileName); var wrapUPlug = nodeFn.findPlug("wrapU"); var wrapU = false; wrapUPlug.getValue(ref wrapU); var wrapVPlug = nodeFn.findPlug("wrapV"); var wrapV = false; wrapVPlug.getValue(ref wrapV); var tex = new MayaM2Texture { WrapU = wrapU, WrapV = wrapV }; mesh.Textures.Add(tex); fileTextureIter.next();//maybe now the loop is fixed } }
public static void StuckNClothTimeWhenNotDynamic(MFnDependencyNode dn) { MPlug plug_isDynamic = dn.findPlug(ConstantValue.plugName_nCloth_isDynamic); MPlug plug_currentTime = dn.findPlug(ConstantValue.plugName_nCloth_currentTime); if (plug_isDynamic != null && plug_currentTime != null) { MPlugArray inputArr_currentTime = new MPlugArray(); plug_currentTime.connectedTo(inputArr_currentTime, true, false); MFnDependencyNode dn_time = new MFnDependencyNode(inputArr_currentTime[0].node); BindAttr.ProjectPlug(plug_isDynamic, dn_time.findPlug(ConstantValue.plugName_nClothTime_nodeState), 0, 1, (int)ConstantValue.TimeNodeState.Stuck, (int)ConstantValue.TimeNodeState.Normal); } }
private bool isNodeNameExcluded(MObject node) { for (int i = 0; i < excludedNamesArray.length; i++) { MFnDependencyNode depNode = new MFnDependencyNode(node); if (excludedNamesArray[i] == depNode.name) { return(true); } } return(false); }
private bool isPBRMaterial(MFnDependencyNode materialDependencyNode) { string graphAttribute = "graph"; if (materialDependencyNode.hasAttribute(graphAttribute)) { string graphValue = materialDependencyNode.findPlug(graphAttribute).asStringProperty; return(graphValue.Contains("stingray")); } else { return(false); } }
public static MPlug getConnection(this MFnDependencyNode mFnDependencyNode, string name) { MPlugArray connections = new MPlugArray(); mFnDependencyNode.getConnections(connections); foreach (MPlug connection in connections) { if (connection.name == (mFnDependencyNode.name + "." + name)) { return(connection); } } return(null); }
void Print(MFnDependencyNode dependencyNode, int logRank, string title) { // prints RaiseVerbose(title, logRank); PrintAttributes(dependencyNode, logRank + 1); RaiseVerbose("Connections", logRank + 1); MPlugArray connections = new MPlugArray(); try { dependencyNode.getConnections(connections); RaiseVerbose("connections.Count=" + connections.Count, logRank + 2); foreach (MPlug connection in connections) { MObject source = connection.source.node; MPlugArray destinations = new MPlugArray(); connection.destinations(destinations); if (source != null && source.hasFn(MFn.Type.kDependencyNode)) { MFnDependencyNode node = new MFnDependencyNode(source); RaiseVerbose("name=" + connection.name + " partialName=" + connection.partialName(false, false, false, true) + " source=" + node.name + " source.apiType=" + source.apiType, logRank + 2); } else { RaiseVerbose("name=" + connection.name, logRank + 2); } RaiseVerbose("destinations.Count=" + destinations.Count, logRank + 3); foreach (MPlug destination in destinations) { MObject destinationObject = destination.node; if (destinationObject != null && destinationObject.hasFn(MFn.Type.kDependencyNode)) { MFnDependencyNode node = new MFnDependencyNode(destinationObject); RaiseVerbose("destination=" + node.name + " destination.apiType=" + destinationObject.apiType, logRank + 3); if (destinationObject.hasFn(MFn.Type.kShadingEngine)) { PrintAttributes(node, logRank + 4); } } } } } catch {} }
public static void BindNCloth(MSelectionList selecteList = null) { if (selecteList == null) { selecteList = BasicFunc.GetSelectedList(); } int count = (int)selecteList.length; if (count <= 1) { //Debug.Log("ncloth control switch target: select [ctl,ncloth0,ncloth1...]"); return; } else { //Debug.Log("ncloth control switch target count:" + count); } MDagPath ctlDag = new MDagPath(); selecteList.getDagPath(0, ctlDag); selecteList.remove(0); MFnDependencyNode dn_ctl = new MFnDependencyNode(ctlDag.node); BasicFunc.IterateSelectedDags((dag) => { //Debug.Log("ncloth control set for:"+dag.fullPathName); MPlug ctlNewAttrPlug = BindAttr.AddBoolAttr(dn_ctl, "Dynamic_" + dag.partialPathName, true, "", false); dag.extendToShape(); MFnDependencyNode dn_nCloth = new MFnDependencyNode(dag.node); MPlug plug_isDynamic = dn_nCloth.findPlug(ConstantValue.plugName_nCloth_isDynamic); MPlug plug_currentTime = dn_nCloth.findPlug(ConstantValue.plugName_nCloth_currentTime); if (plug_isDynamic != null && plug_currentTime != null) { MPlugArray inputArr_currentTime = new MPlugArray(); plug_currentTime.connectedTo(inputArr_currentTime, true, false); MFnDependencyNode dn_time = new MFnDependencyNode(inputArr_currentTime[0].node); BindAttr.ProjectPlug(plug_isDynamic, dn_time.findPlug(ConstantValue.plugName_nClothTime_nodeState), 0, 1, (int)ConstantValue.TimeNodeState.Stuck, (int)ConstantValue.TimeNodeState.Normal); } BasicFunc.ConnectPlug(ctlNewAttrPlug, plug_isDynamic); }, MFn.Type.kNCloth, selecteList); //List<string> nclothNameList = new List<string>(); //foreach (MDagPath dag in nclothList.DagPaths()) //{ // nclothNameList.Add() //} }
public static MFnDependencyNode CreateLayeredTextureNode(List <MFnDependencyNode> imageNodes) { //MFnDependencyNode layeredTextureNode = new MFnDependencyNode(); //layeredTextureNode.create("layeredTexture"); MFnDependencyNode layeredTextureNode = CreateShadingNode(ShadingNodeType.Utility, "layeredTexture"); MPlug layeredTexInputsPlug = layeredTextureNode.findPlug(ConstantValue.plugName_layeredTextureInputs); //check place2DTextures MDGModifier dGModifier = new MDGModifier(); for (int i = 0; i < imageNodes.Count; i++) { //place2dTexture setting MFnDependencyNode p2dNode = GetPlace2dTextureForTex(imageNodes[i]); p2dNode.findPlug("wrapU").setBool(false); p2dNode.findPlug("translateFrameU").setFloat(i); //set tex default color to 0 imageNodes[i].findPlug(ConstantValue.plugName_fileTexDefaultColorR).setFloat(0); imageNodes[i].findPlug(ConstantValue.plugName_fileTexDefaultColorG).setFloat(0); imageNodes[i].findPlug(ConstantValue.plugName_fileTexDefaultColorB).setFloat(0); //move uv MSelectionList matList = GetMaterialsWithTex(imageNodes[i]); for (int j = 0; j < matList.length; j++) { MObject matObj = new MObject(); matList.getDependNode((uint)j, matObj); string matName = new MFnDependencyNode(matObj).absoluteName; Debug.Log("move uv for mat:" + matName); MoveUV(i, 0, matName); } MPlug layeredTexInputPlug = layeredTexInputsPlug.elementByLogicalIndex((uint)i); MPlug texOutColorPlug = imageNodes[i].findPlug(ConstantValue.plugName_fileTexOutputColor); MPlug layeredTexInputColor = layeredTexInputPlug.child((int)ConstantValue.LayeredTextureInputDataIndex.Color); dGModifier.connect(texOutColorPlug, layeredTexInputColor); //set blendMode to add MPlug blendMode = layeredTexInputPlug.child((int)ConstantValue.LayeredTextureInputDataIndex.BlendMode); if (i < imageNodes.Count - 1) { blendMode.setInt((int)ConstantValue.LayeredTextureBlendMode.Add); } else { blendMode.setInt((int)ConstantValue.LayeredTextureBlendMode.None); } } dGModifier.doIt(); return(layeredTextureNode); }
void PrintAttributes(MFnDependencyNode dependencyNode, int logRank) { // prints RaiseVerbose("Attributes", logRank); for (uint i = 0; i < dependencyNode.attributeCount; i++) { MObject attribute = dependencyNode.attribute(i); if (attribute.hasFn(MFn.Type.kAttribute)) { MFnAttribute mFnAttribute = new MFnAttribute(attribute); RaiseVerbose("name=" + mFnAttribute.name + " apiType=" + attribute.apiType, logRank + 1); } } }
private Bitmap LoadTexture(MFnDependencyNode textureDependencyNode) { string sourcePath = getSourcePathFromFileTexture(textureDependencyNode); if (sourcePath == null) { return(null); } if (sourcePath == "") { RaiseError("Texture path is missing for node " + textureDependencyNode.name + ".", logRankTexture + 1); return(null); } return(LoadTexture(sourcePath)); }
private bool isStingrayPBSMaterial(MFnDependencyNode materialDependencyNode) { // TODO - Find a better way to identify material type string graphAttribute = "graph"; if (materialDependencyNode.hasAttribute(graphAttribute)) { string graphValue = materialDependencyNode.findPlug(graphAttribute).asString(); return(graphValue.Contains("stingray")); } else { return(false); } }
public static void Init(MFnDependencyNode babylonAttributesDependencyNode, BabylonPBRMetallicRoughnessMaterial babylonMaterial = null) { babylonMaterialNodeBase.Init(babylonAttributesDependencyNode, babylonMaterial); if (babylonAttributesDependencyNode.hasAttribute("babylonTransparencyMode") == false) { MGlobal.executeCommand($"addAttr -ln \"babylonTransparencyMode\" -nn \"Transparency Mode\" -at \"enum\" -en \"Opaque:Cutoff:Blend:\" {babylonAttributesDependencyNode.name};"); } // Initialise attributes according to babylon material if (babylonMaterial != null) { // Init alpha mode value based on material opacity setAttributeValue(babylonAttributesDependencyNode.name + ".babylonTransparencyMode", babylonMaterial.transparencyMode); } }
/*! * Callback that creates the manipulator if valid geometry is * selected. Also removes the manipulator if no geometry is * selected. Handles connecting the manipulator to multiply * selected nodes. * * \param[in] data Pointer to the current context class. */ void updateManipulators() { deleteManipulators(); if (!validGeometrySelected()) { return; } // Clear info owner = null; firstObjectSelected = MObject.kNullObj; MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); MItSelectionList iter = new MItSelectionList(list, MFn.Type.kInvalid); string manipName = "lineManipContainerCSharp"; MObject manipObject = new MObject(); lineManipContainer manipulator = MPxManipContainer.newManipulator(manipName, manipObject) as lineManipContainer; if (null != manipulator) { // Save state owner = manipulator; // Add the manipulator addManipulator(manipObject); // for (; !iter.isDone; iter.next()) { MObject dependNode = new MObject(); iter.getDependNode(dependNode); MFnDependencyNode dependNodeFn = new MFnDependencyNode(dependNode); // Connect the manipulator to the object in the selection list. manipulator.connectToDependNode(dependNode); // if (MObject.kNullObj == firstObjectSelected) { firstObjectSelected = dependNode; } } // Allow the manipulator to set initial state setInitialState(); } }
public static MSelectionList GetMaterialsWithTex(MFnDependencyNode imageNode) { MPlug plug = imageNode.findPlug(ConstantValue.plugName_fileTexOutputColor); MPlugArray destPlugs = new MPlugArray(); plug.destinations(destPlugs); //BasicFunc.PrintPlugs(destPlugs); MSelectionList newSelection = new MSelectionList(); for (int i = 0; i < destPlugs.length; i++) { newSelection.add(destPlugs[i].node); } //BasicFunc.Select(newSelection); return(newSelection); }
public static bool ConnectPlug(MFnDependencyNode dn_from, string plugName_from, MFnDependencyNode dn_to, string plugName_to, MDGModifier dGModifier = null, bool doit = true) { if (dn_from != null && dn_to != null) { MPlug from = dn_from.findPlug(plugName_from); if (from != null) { MPlug to = dn_to.findPlug(plugName_to); if (to != null) { return(ConnectPlug(from, to, dGModifier, doit)); } } } return(false); }
public static MDagPath CreateCurve(MPointArray points, string curveName, int degree = 1, MFnNurbsCurve.Form form = MFnNurbsCurve.Form.kOpen) { MDoubleArray indices = new MDoubleArray(); for (int i = 0; i < points.Count; i++) { indices.Add(i); } MFnNurbsCurve nc = new MFnNurbsCurve(); MObject curveObject = nc.create(points, indices, (uint)degree, form, false, false); MDagPath curveDagPath = MDagPath.getAPathTo(curveObject); MFnDependencyNode dn = new MFnDependencyNode(curveObject); dn.setName(curveName); return(curveDagPath); }
private void ExportCommonBabylonAttributes(MFnDependencyNode babylonAttributesDependencyNode, BabylonMaterial babylonMaterial) { bool backfaceCulling = babylonAttributesDependencyNode.findPlug("babylonBackfaceCulling").asBool(); RaiseVerbose("backfaceCulling=" + backfaceCulling, 3); babylonMaterial.backFaceCulling = backfaceCulling; int maxSimultaneousLights = babylonAttributesDependencyNode.findPlug("babylonMaxSimultaneousLights").asInt(); RaiseVerbose("maxSimultaneousLights=" + maxSimultaneousLights, 3); babylonMaterial.maxSimultaneousLights = maxSimultaneousLights; bool unlit = babylonAttributesDependencyNode.findPlug("babylonUnlit").asBool(); RaiseVerbose("unlit=" + unlit, 3); babylonMaterial.isUnlit = unlit; }
// The setDependentsDirty() method allows attributeAffects relationships // in a much more general way than via MPxNode::attributeAffects // which is limited to static attributes only. // The setDependentsDirty() method allows relationships to be established // between any combination of dynamic and static attributes. // // Within a setDependentsDirty() implementation you get passed in the // plug which is being set dirty, and then, based upon which plug it is, // you may choose to dirty any other plugs by adding them to the // affectedPlugs list. // // In almost all cases, the relationships you set up will be fixed for // the duration of Maya, such as "A affects B". However, you can also // set up relationships which depend upon some external factor, such // as the current frame number, the time of day, if maya was invoked in // batch mode, etc. These sorts of relationships are straightforward to // implement in your setDependentsDirty() method. // // There may also be situations where you need to look at values in the // dependency graph. It is VERY IMPORTANT that when accessing DG values // you do not cause a DG evaluation. This is because your setDependentsDirty() // method is called during dirty processing and causing an evalutaion could // put Maya into an infinite loop. The only safe way to look at values // on plugs is via the MDataBlock::outputValue() which does not trigger // an evaluation. It is recommeneded that you only look at plugs whose // values are constant or you know have already been computed. // // For this example routine, we will only implement the simplest case // of a relationship. // public override void setDependentsDirty(MPlug plugBeingDirtied, MPlugArray affectedPlugs) { MObject thisNode = thisMObject(); MFnDependencyNode fnThisNode = new MFnDependencyNode(thisNode); if (plugBeingDirtied.partialName() == "A") { // "A" is dirty, so mark "B" dirty if "B" exists. // This implements the relationship "A affects B". // MGlobal.displayInfo("affects::setDependentsDirty, \"A\" being dirtied"); MPlug pB = fnThisNode.findPlug("B"); MGlobal.displayInfo("\t\t... dirtying \"B\"\n"); affectedPlugs.append(pB); } return; }
private MFnDependencyNode getBabylonMaterialNode(MFnDependencyNode materialDependencyNode) { // Retreive connection MPlug connectionOutColor = materialDependencyNode.getConnection("outColor"); MPlugArray destinations = new MPlugArray(); connectionOutColor.destinations(destinations); // Retreive all Babylon Attributes dependency nodes List <MFnDependencyNode> babylonAttributesNodes = new List <MFnDependencyNode>(); foreach (MPlug destination in destinations) { MObject destinationObject = destination.node; if (destinationObject != null && destinationObject.hasFn(MFn.Type.kPluginHardwareShader)) { MFnDependencyNode babylonAttributesDependencyNode = new MFnDependencyNode(destinationObject); if (babylonAttributesDependencyNode.typeId.id == babylonStandardMaterialNode.id || babylonAttributesDependencyNode.typeId.id == babylonStingrayPBSMaterialNode.id || babylonAttributesDependencyNode.typeId.id == babylonAiStandardSurfaceMaterialNode.id) { babylonAttributesNodes.Add(babylonAttributesDependencyNode); } } } if (babylonAttributesNodes.Count == 0) { return(null); } else { // Occurs only if the user explicitly create a connection with several babylon attributes nodes. if (babylonAttributesNodes.Count > 1) { RaiseWarning("Babylon attributes node attached to a material should be unique. The first one is going to be used.", 2); } // Return the first shading engine node return(babylonAttributesNodes[0]); } }
override public void doIt(MArgList args) { MGlobal.displayInfo("doIt..."); MSelectionList selectList = MGlobal.activeSelectionList; foreach( MObject node in selectList.DependNodes() ) { MFnDependencyNode depFn = new MFnDependencyNode(); depFn.setObject(node); MGlobal.displayInfo("Name: " + depFn.name); MGlobal.displayInfo("Type: " + node.apiTypeStr); MGlobal.displayInfo("Function Sets: "); foreach (string st in MGlobal.getFunctionSetList(node)) MGlobal.displayInfo(st + ", "); MGlobal.displayInfo(""); } return; }
public override void doIt(MArgList args) { MTypeId id = new MTypeId(0x0008106c); MObject setNode = fDGMod.createNode(id); fDGMod.doIt(); MSelectionList selList = new MSelectionList(); MGlobal.getActiveSelectionList( selList ); if( selList.length > 0 ) { try { MFnSet setFn = new MFnSet(setNode); setFn.addMembers(selList); } catch (System.Exception) { } } MFnDependencyNode depNodeFn = new MFnDependencyNode( setNode ); setResult( depNodeFn.name ); return; }
// // Maya calls this method to have the translator write out a file. // public override void writer(MFileObject file, string optionsString, MPxFileTranslator.FileAccessMode mode) { // // For simplicity, we only do full saves/exports. // if ((mode != MPxFileTranslator.FileAccessMode.kSaveAccessMode) && (mode != MPxFileTranslator.FileAccessMode.kExportAccessMode)) throw new System.NotImplementedException( "We only support support SaveAccessMode and ExportAccessMode"); // // Let's see if we can open the output file. // FileStream output = null; try { output = new FileStream(file.fullName, FileMode.Create, FileAccess.Write); } catch (ArgumentException ex) { MGlobal.displayInfo("File access invalid!"); if(output != null) output.Close(); throw ex; } // // Get some node flags to keep track of those nodes for which we // have already done various stages of processing. // fCreateFlag = MFnDependencyNode.allocateFlag(fPluginName); fAttrFlag = MFnDependencyNode.allocateFlag(fPluginName); fConnectionFlag = MFnDependencyNode.allocateFlag(fPluginName); // // Run through all of the nodes in the scene and clear their flags. // MItDependencyNodes nodesIter = new MItDependencyNodes(); for (; !nodesIter.isDone; nodesIter.next()) { MObject node = nodesIter.item; MFnDependencyNode nodeFn = new MFnDependencyNode(node); nodeFn.setFlag(fCreateFlag, false); nodeFn.setFlag(fAttrFlag, false); nodeFn.setFlag(fConnectionFlag, false); } // // Write out the various sections of the file. // writeHeader(output, file.name); writeFileInfo(output); writeReferences(output); writeRequirements(output); writeUnits(output); writeDagNodes(output); writeNonDagNodes(output); writeDefaultNodes(output); writeReferenceNodes(output); writeConnections(output); writeFooter(output, file.name); output.Close(); MFnDependencyNode.deallocateFlag(fPluginName, fCreateFlag); return; }
protected void getSetAttrCmds(MObject node, MStringArray cmds) { // // Get rid of any garbage already in the array. // cmds.clear(); // // Run through the node's attributes. // MFnDependencyNode nodeFn = new MFnDependencyNode(node); uint numAttrs = nodeFn.attributeCount; uint i; for (i = 0; i < numAttrs; i++) { // // Use the attribute ordering which Maya uses when doing I/O. // MObject attr = nodeFn.reorderedAttribute(i); MFnAttribute attrFn = new MFnAttribute(attr); bool isChild; attrFn.parent(out isChild); // // We don't want attributes which are children of other attributes // because they will be processed when we process the parent. // // And we only want storable attributes which accept inputs. // if (!isChild && attrFn.isStorable && attrFn.isWritable) { // // Get a plug for the attribute. // MPlug plug = new MPlug(node, attr); // // Get setAttr commands for this attribute, and any of its // children, which have had their values changed by the scene. // MStringArray newCmds = new MStringArray(); plug.getSetAttrCmds(newCmds, MPlug.MValueSelector.kChanged, false); uint numCommands = newCmds.length; int c; for (c = 0; c < numCommands; c++) { if (newCmds[c] != "") cmds.append(newCmds[c]); } } } }
private bool isNodeNameExcluded(MObject node) { for (int i = 0; i < excludedNamesArray.length; i++) { MFnDependencyNode depNode = new MFnDependencyNode(node); if (excludedNamesArray[i] == depNode.name) { return true; } } return false; }
// // 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); } } }
public bool getExCameraSetNode(MObject dirObj) { // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; list.getDependNode(0, dirNode); if (dirNode == MObject.kNullObj) return false; MFnDependencyNode nodeFn = new MFnDependencyNode(dirNode); if (nodeFn.typeId.id != exCameraSet.type_id.id) return false; dirObj = dirNode; return true; }
private void dumpInfo(MObject fileNode, MFnDependencyNode nodeFn, MObjectArray nodePath) { MObject fileAttr = nodeFn.attribute("fileTextureName"); MPlug plugToFile = new MPlug(fileNode, fileAttr); MFnDependencyNode dgFn = new MFnDependencyNode(); MGlobal.displayInfo("Name: " + nodeFn.name); MObject fnameValue = new MObject(); try { plugToFile.getValue(fnameValue); } catch (Exception) { MGlobal.displayInfo("error getting value from plug"); return; } MFnStringData stringFn = new MFnStringData(fnameValue); MGlobal.displayInfo("Texture: " + stringFn.stringProperty); string path = "Path: "; for (int i = (int)nodePath.length - 1; i >= 0; i--) { MObject currentNode = nodePath[i]; dgFn.setObject(currentNode); path += dgFn.name + "(" + dgFn.typeName + ")"; if (i > 0) path += " -> "; } MGlobal.displayInfo(path); }
// // Write out the 'addAttr' and 'setAttr' commands for a node. // protected void writeNodeAttrs(FileStream f, MObject node, bool isSelected) { MFnDependencyNode nodeFn = new MFnDependencyNode(node); if (nodeFn.canBeWritten) { MStringArray addAttrCmds = new MStringArray(); MStringArray setAttrCmds = new MStringArray(); getAddAttrCmds(node, addAttrCmds); getSetAttrCmds(node, setAttrCmds); uint numAddAttrCmds = addAttrCmds.length; uint numSetAttrCmds = setAttrCmds.length; if (numAddAttrCmds + numSetAttrCmds > 0) { // // If the node is not already selected, then issue a command to // select it. // if (!isSelected) writeSelectNode(f, node); int i; string result = ""; for (i = 0; i < numAddAttrCmds; i++) result += (addAttrCmds[i] + "\n"); for (i = 0; i < numSetAttrCmds; i++) result += (setAttrCmds[i] + "\n"); writeString(f, result); } } }
//====================================================================== // // 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 ); } } } } } }
public override void doIt(MArgList args) { MSelectionList list = new MSelectionList(); if ( args.length > 0 ) { // Arg list is > 0 so use objects that were passes in // uint last = args.length; for ( uint i = 0; i < last; i++ ) { // Attempt to find all of the objects matched // by the string and add them to the list // string argStr = args.asString(i); list.add(argStr); } } else { // Get arguments from Maya's selection list. MGlobal.getActiveSelectionList(list); } MObject node = new MObject(); MObjectArray nodePath = new MObjectArray(); MFnDependencyNode nodeFn = new MFnDependencyNode(); MFnDependencyNode dgNodeFnSet = new MFnDependencyNode(); for (MItSelectionList iter = new MItSelectionList(list); !iter.isDone; iter.next()) { iter.getDependNode(node); // // The following code shows how to navigate the DG manually without // using an iterator. First, find the attribute that you are // interested. Then connect a plug to it and see where the plug // connected to. Once you get all the connections, you can choose // which route you want to go. // // In here, we wanted to get to the nodes that instObjGroups connected // to since we know that the shadingEngine connects to the instObjGroup // attribute. // nodeFn.setObject( node ); MObject iogAttr = null; try { iogAttr = nodeFn.attribute("instObjGroups"); } catch (Exception) { MGlobal.displayInfo(nodeFn.name + ": is not a renderable object, skipping"); continue; } MPlug iogPlug = new MPlug(node, iogAttr); MPlugArray iogConnections = new MPlugArray(); // // instObjGroups is a multi attribute. In this example, just the // first connection will be tried. // if (!iogPlug.elementByLogicalIndex(0).connectedTo(iogConnections, false, true)) { MGlobal.displayInfo(nodeFn.name + ": is not in a shading group, skipping"); continue; } // // Now we would like to traverse the DG starting from the shadingEngine // since most likely all file texture nodes will be found. Note the // filter used to initialize the DG iterator. There are lots of filter // type available in MF.Type that you can choose to suite your needs. // bool foundATexture = false; for ( int i=0; i < iogConnections.length; i++ ) { MObject currentNode = iogConnections[i].node; // // Note that upon initialization, the current pointer of the // iterator already points to the first valid node. // MItDependencyGraph dgIt = new MItDependencyGraph(currentNode, MFn.Type.kFileTexture, MItDependencyGraph.Direction.kUpstream, MItDependencyGraph.Traversal.kBreadthFirst, MItDependencyGraph.Level.kNodeLevel); if (dgIt == null) { continue; } dgIt.disablePruningOnFilter(); for ( ; !dgIt.isDone; dgIt.next() ) { MObject thisNode = dgIt.thisNode(); dgNodeFnSet.setObject(thisNode); try { dgIt.getNodePath(nodePath); } catch (Exception) { MGlobal.displayInfo("getNodePath"); continue; } // // append the starting node. // nodePath.append(node); dumpInfo( thisNode, dgNodeFnSet, nodePath ); foundATexture = true; } } if ( !foundATexture ) { MGlobal.displayInfo(nodeFn.name + ": is not connected to a file texture"); } } return; }
// get the plug at the node MPlug getPlug(string node_name, string attribute_name) { MFnDependencyNode dn = new MFnDependencyNode(getDependNode(node_name)); MPlug pl = dn.findPlug(attribute_name); return pl; }
//! Ensure that valid geometry is selected bool validGeometrySelected() { MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); MItSelectionList iter = new MItSelectionList(list, MFn.Type.kInvalid); for (; !iter.isDone; iter.next()) { MObject dependNode = new MObject(); iter.getDependNode(dependNode); if (dependNode.isNull || !dependNode.hasFn(MFn.Type.kTransform)) { MGlobal.displayWarning("Object in selection list is not right type of node"); return false; } MFnDependencyNode dependNodeFn = new MFnDependencyNode(dependNode); MStringArray attributeNames = new MStringArray(); attributeNames.append("scaleX"); attributeNames.append("translateX"); int i; for ( i = 0; i < attributeNames.length; i++ ) { MPlug plug = dependNodeFn.findPlug(attributeNames[i]); if ( plug.isNull ) { MGlobal.displayWarning("Object cannot be manipulated: " + dependNodeFn.name); return false; } } } return true; }
/*! Callback that creates the manipulator if valid geometry is selected. Also removes the manipulator if no geometry is selected. Handles connecting the manipulator to multiply selected nodes. \param[in] data Pointer to the current context class. */ void updateManipulators() { deleteManipulators(); if ( ! validGeometrySelected() ) { return; } // Clear info owner = null; firstObjectSelected = MObject.kNullObj; MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); MItSelectionList iter = new MItSelectionList(list, MFn.Type.kInvalid); string manipName = "lineManipContainerCSharp"; MObject manipObject = new MObject(); lineManipContainer manipulator = MPxManipContainer.newManipulator(manipName, manipObject) as lineManipContainer; if (null != manipulator) { // Save state owner = manipulator; // Add the manipulator addManipulator(manipObject); // for (; !iter.isDone; iter.next()) { MObject dependNode = new MObject(); iter.getDependNode(dependNode); MFnDependencyNode dependNodeFn = new MFnDependencyNode(dependNode); // Connect the manipulator to the object in the selection list. manipulator.connectToDependNode(dependNode); // if (MObject.kNullObj == firstObjectSelected) { firstObjectSelected = dependNode; } } // Allow the manipulator to set initial state setInitialState(); } }
protected void writeNonDagNodes(FileStream f) { MItDependencyNodes nodeIter = new MItDependencyNodes(); for (; !nodeIter.isDone; nodeIter.next()) { MObject node = nodeIter.item; MFnDependencyNode nodeFn = new MFnDependencyNode(node); // // Save default nodes for later processing. // if (nodeFn.isDefaultNode) { fDefaultNodes.append(node); } else if (!nodeFn.isFromReferencedFile && !nodeFn.isFlagSet(fCreateFlag)) { // // If this node is either writable or shared, then write it out. // Otherwise don't, but still mark it as having been written so // that we don't end up processing it again at some later time. // if (nodeFn.canBeWritten || nodeFn.isShared) { writeCreateNode(f, node); writeNodeAttrs(f, node, true); writeLockNode(f, node); } nodeFn.setFlag(fCreateFlag, true); nodeFn.setFlag(fAttrFlag, true); } } }
// // Write the 'connectAttr' commands for all of a node's incoming // connections. // protected void writeNodeConnections(FileStream f, MObject node) { MFnDependencyNode nodeFn = new MFnDependencyNode(node); MPlugArray plugs = new MPlugArray(); try { nodeFn.getConnections(plugs); } catch (Exception) { } uint numBrokenConns = fBrokenConnSrcs.length; uint numPlugs = plugs.length; int i; string result = ""; for (i = 0; i < numPlugs; i++) { // // We only care about connections where we are the destination. // MPlug destPlug = plugs[i]; MPlugArray srcPlug = new MPlugArray(); destPlug.connectedTo(srcPlug, true, false); if (srcPlug.length > 0) { MObject srcNode = srcPlug[0].node; MFnDependencyNode srcNodeFn = new MFnDependencyNode(srcNode); // // Don't write the connection if the source is not writable... // if (!srcNodeFn.canBeWritten) continue; // // or the connection was made in a referenced file... // if (destPlug.isFromReferencedFile) continue; // // or the plug is procedural... // if (destPlug.isProcedural) continue; // // or it is a connection between a default node and a shared // node (because those will get set up automatically). // if (srcNodeFn.isDefaultNode && nodeFn.isShared) continue; result += "connectAttr \""; // // Default nodes get a colon at the start of their names. // if (srcNodeFn.isDefaultNode) result += ":"; result += (srcPlug[0].partialName(true) + "\" \""); if (nodeFn.isDefaultNode) result += ":"; result += (destPlug.partialName(true) + "\""); // // If the src plug is also one from which a broken // connection originated, then add the "-rd/referenceDest" flag // to the command. That will help Maya to better adjust if the // referenced file has changed the next time it is loaded. // if (srcNodeFn.isFromReferencedFile) { int j; for (j = 0; j < numBrokenConns; j++) { if (fBrokenConnSrcs[j] == srcPlug[0]) { result += (" -rd \"" + fBrokenConnDests[j].partialName(true) + "\""); break; } } } // // If the plug is locked, then add a "-l/lock" flag to the // command. // if (destPlug.isLocked) result += " -l on"; // // If the destination attribute is a multi for which index // does not matter, then we must add the "-na/nextAvailable" // flag to the command. // MObject attr = destPlug.attribute; MFnAttribute attrFn = new MFnAttribute(attr); if (!attrFn.indexMatters) result += " -na"; result += (";" + "\n"); } } writeString(f, result); }
protected void writeDefaultNodes(FileStream f) { uint numNodes = fDefaultNodes.length; int i; for (i = 0; i < numNodes; i++) { writeNodeAttrs(f, fDefaultNodes[i], false); MFnDependencyNode nodeFn = new MFnDependencyNode(fDefaultNodes[i]); nodeFn.setFlag(fAttrFlag, true); } }
// // Write out a 'createNode' command for a non-DAG node. // protected void writeCreateNode(FileStream f, MObject node) { MFnDependencyNode nodeFn = new MFnDependencyNode(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 + "\";" + "\n"); writeString(f, result); }
protected void writeReferenceNodes(FileStream f) { // // We don't write out createNode commands for reference nodes, but // we do write out parenting between them and non-reference nodes, // as well as attributes added and attribute values changed after the // referenced file was loaded // writeRefNodeParenting(f); // // Output the commands for DAG nodes first. // MItDag dagIter = new MItDag(); for (dagIter.next(); !dagIter.isDone; dagIter.next()) { MObject node = dagIter.item(); MFnDependencyNode nodeFn = new MFnDependencyNode(node); if (nodeFn.isFromReferencedFile && !nodeFn.isFlagSet(fAttrFlag)) { writeNodeAttrs(f, node, false); // // Make note of any connections to this node which have been // broken by the main scene. // MFileIO.getReferenceConnectionsBroken( node, fBrokenConnSrcs, fBrokenConnDests, true, true ); nodeFn.setFlag(fAttrFlag, true); } } // // Now do the remaining, non-DAG nodes. // MItDependencyNodes nodeIter = new MItDependencyNodes(); for (; !nodeIter.isDone; nodeIter.next()) { MObject node = nodeIter.item; MFnDependencyNode nodeFn = new MFnDependencyNode(node); if (nodeFn.isFromReferencedFile && !nodeFn.isFlagSet(fAttrFlag)) { writeNodeAttrs(f, node, false); // // Make note of any connections to this node which have been // broken by the main scene. // MFileIO.getReferenceConnectionsBroken( node, fBrokenConnSrcs, fBrokenConnDests, true, true ); nodeFn.setFlag(fAttrFlag, true); } } }
// // Write out a "lockNode" command. // protected void writeLockNode(FileStream f, MObject node) { MFnDependencyNode nodeFn = new MFnDependencyNode(node); // // By default, nodes are not locked, so we only have to issue a // "lockNode" command if the node is locked. // if (nodeFn.isLocked) writeString(f, "lockNode;\n"); }
//====================================================================== // // 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 ); } }
// // 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); }
// Parses the given command line arguments and executes them. // public override void doIt(MArgList args) { parseArgs(args); bool nothingSet = (!createdUsed && !appendCameraUsed && !appendCameraAndSetUsed && !deleteLayerUsed && !cameraUsed && !layerUsed && !helpUsed && !setUsed && !layerTypeUsed && !numLayersUsed); if (nothingSet) { throw new ArgumentException("A flag must be used. testCameraSet -help for available flags", "args"); } if (helpUsed) { MGlobal.displayInfo("testExCameraSet -help"); MGlobal.displayInfo("\ttestExCameraSet tests the functionality of the exCameraSet node."); MGlobal.displayInfo(""); MGlobal.displayInfo("\t-h -help : This message is printed"); MGlobal.displayInfo("\t-a -active [true/false]: Set/get whether a particular layer is active"); MGlobal.displayInfo("\t-ac -appendCamera <cameraName>: Append a new camera layer to the cameraSet using the specified camera"); MGlobal.displayInfo("\t-acs -appendCameraAndSet <cameraName> <setName>: Append a new camera layer to the cameraSet using the specified camera and set"); MGlobal.displayInfo("\t-cam -camera [<cameraName>]: Set/get the camera for a particular layer"); MGlobal.displayInfo("\t-c -create : Create a new cameraSet node"); MGlobal.displayInfo("\t-d -deleteLayer <layerIndex>: Delete the layer at the given index"); MGlobal.displayInfo("\t-nl -numLayers: Returns the number of layers defined in the specified cameraSet"); MGlobal.displayInfo("\t-l -layer <layerIndex>: Specifies the layer index to be used when accessing layer information"); MGlobal.displayInfo("\t-lt -layerType [<layerTypeName>]: Set/get the layer type for a particular layer. Possible values are Mono, Left, and Right."); MGlobal.displayInfo("\t-s -set [<setName>]: Set/get the set for a particular layer"); MGlobal.displayInfo("\t-e -edit : Perform an edit operation"); MGlobal.displayInfo("\t-q -query : Perform a query operation"); MGlobal.displayInfo(""); } uint nObjs = list.length; if (nObjs == 0) { if (createdUsed) { // Create a new cameraSet node. // MFnDependencyNode dirFn = new MFnDependencyNode(); string noName = ""; try { MObject dirObj = dirFn.create(exCameraSet.type_id, noName); MGlobal.select(dirObj, MGlobal.ListAdjustment.kReplaceList); } catch (System.Exception ex) { throw new ApplicationException("Could not create a cameraSet node", ex); } return; } if (appendCameraUsed || appendCameraAndSetUsed || deleteLayerUsed || editUsed || cameraUsed || setUsed || layerTypeUsed || activeUsed || numLayersUsed) { throw new ArgumentException("Must specify a cameraSet node", "args"); } } else { if (createdUsed) { throw new ArgumentException("-create cannot have any object specified", "args"); } if (appendCameraUsed) { if (nObjs != 1) { throw new ArgumentException("-appendCamera must have a single cameraSet node specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-appendCamera must have a valid exCameraSet node specified", "args"); } // Get a dag path to the specified camera. // MSelectionList camList = new MSelectionList(); camList.add(camName); MDagPath camPath = new MDagPath(); camList.getDagPath(0, camPath); if (!camPath.isValid) { throw new ArgumentException("-appendCamera must have a valid camera node specified", "args"); } // Call the MFnCameraSet method to append the layer. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.appendLayer(camPath, MObject.kNullObj); return; } if (appendCameraAndSetUsed) { if (nObjs != 1) { throw new ArgumentException("-appendCameraAndSet must have a single cameraSet node specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-appendCameraAndSet must have a valid exCameraSet node specified", "args"); } // Get a dag path to the specified camera. // MSelectionList camList = new MSelectionList(); camList.add(camName); MDagPath camPath = new MDagPath(); camList.getDagPath(0, camPath); if (!camPath.isValid) { throw new ArgumentException("-appendCameraAndSet must have a valid camera node specified", "args"); } // Get the specified set node. // MSelectionList setList = new MSelectionList(); setList.add(setName); MObject setObj = MObject.kNullObj; setList.getDependNode(0, setObj); if (setObj == MObject.kNullObj) { throw new ArgumentException("-appendCameraAndSet must have a valid set node specified", "args"); } // Call the MFnCameraSet method to append the layer. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.appendLayer(camPath, setObj); return; } if (deleteLayerUsed) { if (nObjs != 1) { throw new ArgumentException("-deleteLayer must have a single cameraSet node specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-deleteLayer must have a valid exCameraSet node specified", "args"); } // Call the MFnCameraSet method to delete the layer. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.deleteLayer((uint)cameraLayer); return; } if (numLayersUsed) { if (queryUsed) { // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-numLayers must have a valid exCameraSet node specified", "args"); } // Call the MFnCameraSet method to get the number of layers. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); uint numLayers = dirFn.numLayers; setResult((int)numLayers); } else { throw new ArgumentException("-numLayers requires the query flag to be used", "args"); } return; } if (cameraUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-camera must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-camera must have a valid exCameraSet node specified", "args"); } if (editUsed) { // Get a dag path to the specified camera. // MSelectionList camList = new MSelectionList(); camList.add(camName); MDagPath camPath = new MDagPath(); camList.getDagPath(0, camPath); if (!camPath.isValid) { throw new ArgumentException("-camera must have a valid camera node specified", "args"); } // Call the MFnCameraSet method to set the camera. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.setLayerCamera((uint)cameraLayer, camPath); } else if (queryUsed) { // Call the MFnCameraSet method to get the camera. // MDagPath camPath = new MDagPath(); MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.getLayerCamera((uint)cameraLayer, camPath); MObject camNode = camPath.node; MFnDependencyNode nodeFn = new MFnDependencyNode(camNode); setResult(nodeFn.name); } } if (setUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-set must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-set must have a valid exCameraSet node specified", "args"); } if (editUsed) { // Get the specified set node. // MObject setObj = MObject.kNullObj; if (setName != "") { MSelectionList setList = new MSelectionList(); setList.add(setName); setList.getDependNode(0, setObj); if (setObj == MObject.kNullObj) { throw new ArgumentException("-set must have a valid set node specified", "args"); } } // Call the MFnCameraSet method to set the set node. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.setLayerSceneData((uint)cameraLayer, setObj); } else if (queryUsed) { // Call the MFnCameraSet method to get the set node. // MObject setObj = new MObject(); MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.getLayerSceneData((uint)cameraLayer, setObj); MFnDependencyNode nodeFn = new MFnDependencyNode(setObj); setResult(nodeFn.name); } } if (layerTypeUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-layerType must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-layerType must have a valid exCameraSet node specified", "args"); } MFnDependencyNode nodeFn = new MFnDependencyNode(dirNode); exCameraSet exDir = nodeFn.userNode as exCameraSet; if (editUsed) { // Get the specified layer type. // int pt = -1; if (layerTypeVal == "Mono") pt = 0; else if (layerTypeVal == "Left") pt = 1; else if (layerTypeVal == "Right") pt = 2; else { throw new ArgumentException("-layerType must have a valid type specified", "args"); } // Call the exCameraSet method to set the layer type. // exDir.setLayerType((uint)cameraLayer, pt); } else if (queryUsed) { // Call the exCameraSet method to get the layer type. // try { int lt = exDir.getLayerType((uint)cameraLayer); if (lt == 0) setResult("Mono"); else if (lt == 1) setResult("Left"); else if (lt == 2) setResult("Right"); } catch (System.Exception ex) { throw new ApplicationException("exCameraSet node does not have a valid layer type", ex); } } } if (activeUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-active must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-active must have a valid exCameraSet node specified", "args"); } if (editUsed) { // Call the MFnCameraSet method to set the set node. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.setLayerActive((uint)cameraLayer, activeVal); } else if (queryUsed) { // Call the MFnCameraSet method to get the active value. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); activeVal = dirFn.isLayerActive((uint)cameraLayer); setResult(activeVal); } } } return; }
protected void getAddAttrCmds(MObject node, MStringArray cmds) { // // Run through the node's attributes. // MFnDependencyNode nodeFn = new MFnDependencyNode(node); uint numAttrs = nodeFn.attributeCount; uint i; for (i = 0; i < numAttrs; i++) { // // Use the attribute ordering which Maya uses when doing I/O. // MObject attr = nodeFn.reorderedAttribute(i); // // If this attribute has been added since the node was created, // then we may want to write out an addAttr statement for it. // if (nodeFn.isNewAttribute(attr)) { MFnAttribute attrFn = new MFnAttribute(attr); // // If the attribute has a parent then ignore it because it will // be processed when we process the parent. // bool bFound; attrFn.parent(out bFound); if ( !bFound ) { // // If the attribute is a compound, then we can do its entire // tree at once. // try { MFnCompoundAttribute cAttrFn = new MFnCompoundAttribute(attr); MStringArray newCmds = new MStringArray(); cAttrFn.getAddAttrCmds(newCmds); uint numCommands = newCmds.length; int c; for (c = 0; c < numCommands; c++) { if (newCmds[c] != "") cmds.append(newCmds[c]); } } catch (Exception) { string newCmd = attrFn.getAddAttrCmd(); if (newCmd != "") cmds.append(newCmd); } } } } }
public static void updateManipulators(RotateManipContext ctx) { if (ctx == null) return; ctx.deleteManipulators(); // Add the rotate manipulator to each selected object. This produces // behavior different from the default rotate manipulator behavior. Here, // a distinct rotate manipulator is attached to every object. // try { MSelectionList list = MGlobal.activeSelectionList; MItSelectionList iter = new MItSelectionList(list, MFn.Type.kInvalid); for (; !iter.isDone; iter.next()) { // Make sure the selection list item is a depend node and has the // required plugs before manipulating it. // MObject dependNode = new MObject(); iter.getDependNode(dependNode); if (dependNode.isNull || !dependNode.hasFn(MFn.Type.kDependencyNode)) { MGlobal.displayWarning("Object in selection list is not a depend node."); continue; } MFnDependencyNode dependNodeFn = new MFnDependencyNode(dependNode); try { /* MPlug rPlug = */ dependNodeFn.findPlug("rotate"); } catch (System.Exception) { MGlobal.displayWarning("Object cannot be manipulated: " + dependNodeFn.name); continue; } // Add manipulator to the selected object // MObject manipObject = new MObject(); exampleRotateManip manipulator; try { manipulator = exampleRotateManip.newManipulator("exampleRotateManipCSharp", manipObject) as exampleRotateManip; // Add the manipulator // ctx.addManipulator(manipObject); // Connect the manipulator to the object in the selection list. // try { manipulator.connectToDependNode(dependNode); } catch (System.Exception) { MGlobal.displayWarning("Error connecting manipulator to object: " + dependNodeFn.name); } } catch (System.Exception) { } } } catch (System.Exception) { } }
protected override bool writesCreateNode(MObject node) { bool result = false; MFnDependencyNode depNode = new MFnDependencyNode(node); if (depNode.isFromReferencedFile && !outputReferences) { return false; } if (isNodeNameExcluded(node)) { return false; } if (!result) { result = isNodeTypeIncluded(node.apiTypeStr); } return result; }