Beispiel #1
0
        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);
        }
Beispiel #2
0
        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);
        }
Beispiel #3
0
        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);
        }
Beispiel #4
0
        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);
        }
Beispiel #5
0
        /// <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);
            }
        }
Beispiel #7
0
        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);
        }
        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()
            //}
        }
Beispiel #9
0
        // get the plug at the node
        public MPlug getPlug(string node_name, string attribute_name)
        {
            var dn = new MFnDependencyNode(getDependNode(node_name));
            var pl = dn.findPlug(attribute_name);

            return(pl);
        }
Beispiel #10
0
        // 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);
        }
Beispiel #11
0
        public static void DeleteUnusedShadingNode(MSelectionList list)
        {
            if (list == null)
            {
                Debug.Log("list null");
                return;
            }
            List <MFnDependencyNode> deleteList = new List <MFnDependencyNode>();

            for (int i = 0; i < list.length; i++)
            {
                MObject mo = new MObject();
                list.getDependNode((uint)i, mo);
                if (mo.hasFn(MFn.Type.kShadingEngine))
                {
                    MFnDependencyNode sgNode = new MFnDependencyNode(mo);
                    MPlug             plug_dagSetMemebers = sgNode.findPlug(ConstantValue.plugName_dagSetMembers);
                    Debug.Log("numelements:" + plug_dagSetMemebers.numElements);
                    if (plug_dagSetMemebers.numElements == 0)
                    {
                        deleteList.Add(sgNode);
                    }
                }
                //Debug.Log(sgNode.name);
            }
            BasicFunc.DeleteObjects(deleteList);
        }
Beispiel #12
0
        private MFnDependencyNode getTextureDependencyNode(MFnDependencyNode materialDependencyNode, string plugName)
        {
            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++;
                return(getTextureDependencyNode(textureDependencyNode, "bumpValue"));
            }

            // If a reverse node is used as an intermediate node
            if (sourceObject.hasFn(MFn.Type.kReverse))
            {
                // TODO - reverse?
                logRankTexture++;
                return(getTextureDependencyNode(textureDependencyNode, "input"));
            }

            return(textureDependencyNode);
        }
Beispiel #13
0
        public MObject findShadingEngine(MObject node)
        //
        //	Description:
        //		Given the material MObject this method will
        //	return the shading group that it is assigned to.
        //	if there is no shading group associated with
        //	the material than a null MObject is apssed back.
        //
        {
            MFnDependencyNode nodeFn          = new MFnDependencyNode(node);
            MPlug             srcPlug         = nodeFn.findPlug("outColor");
            MPlugArray        nodeConnections = new MPlugArray();

            srcPlug.connectedTo(nodeConnections, false, true);
            //loop through the connections
            //and find the shading engine node that
            //it is connected to
            //
            for (int i = 0; i < nodeConnections.length; i++)
            {
                if (nodeConnections[i].node.hasFn(MFn.Type.kShadingEngine))
                {
                    return(nodeConnections[i].node);
                }
            }

            //no shading engine associated so return a
            //null MObject
            //
            return(new MObject());
        }
Beispiel #14
0
        //
        //    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);
            }
        }
Beispiel #15
0
		// 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;
		}
Beispiel #16
0
        public static MFnDependencyNode GetPlace2dTextureForTex(MFnDependencyNode imageNode, bool createIfNotExist = true)
        {
            if (imageNode == null)
            {
                Debug.Log("image Node null");
                return(null);
            }
            MPlug      uvPlug      = imageNode.findPlug(ConstantValue.plugName_texFileUVCoord);
            MPlugArray sourcePlugs = new MPlugArray();

            uvPlug.connectedTo(sourcePlugs, true, false);
            if (sourcePlugs.length == 0)
            {
                //no input
                if (createIfNotExist)
                {
                    MFnDependencyNode place2dTexNode = CreateShadingNode(ShadingNodeType.Utility, "place2dTexture");
                    MPlug             p2tUVOut       = place2dTexNode.findPlug(ConstantValue.plugName_place2dOutUV);
                    string            nodeName       = place2dTexNode.absoluteName;
                    MDGModifier       dgModifier     = new MDGModifier();
                    dgModifier.connect(p2tUVOut, uvPlug);
                    dgModifier.doIt();
                    return(place2dTexNode);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(new MFnDependencyNode(sourcePlugs[0].node));
            }
        }
Beispiel #17
0
        private static List <Material> GetMaterialsMesh(ref MFnMesh Mesh, ref MDagPath Path)
        {
            // Get materials for this mesh
            var Result = new List <Material>();

            // Fetch data
            var Shaders       = new MObjectArray();
            var ShaderIndices = new MIntArray();

            Mesh.getConnectedShaders(Path.instanceNumber, Shaders, ShaderIndices);

            // Iterate and add
            for (int i = 0; i < (int)Shaders.length; i++)
            {
                // Find plug
                var ShaderNode = new MFnDependencyNode(Shaders[i]);
                var ShaderPlug = ShaderNode.findPlug("surfaceShader");
                var MatPlug    = new MPlugArray();
                ShaderPlug.connectedTo(MatPlug, true, false);

                if (MatPlug.length > 0)
                {
                    Result.Add(new Material(CleanNodeName(new MFnDependencyNode(MatPlug[0].node).name)));
                }
            }

            return(Result);
        }
Beispiel #18
0
        /// <summary>
        /// Originally written in C++ by RobTheBloke.
        /// See https://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/research/maya/mfnmesh.htm
        /// </summary>
        /// <param name="shadingEngine"></param>
        /// <returns>The shader name.</returns>
        private static MObjectArray GetMaterials(MObject shadingEngine)
        {
            // attach a function set to the shading engine
            var fn = new MFnDependencyNode(shadingEngine);

            // get access to the surfaceShader attribute. This will be connected to
            // lambert , phong nodes etc.
            var sShader = fn.findPlug("surfaceShader");

            // will hold the connections to the surfaceShader attribute
            var materials = new MPlugArray();

            // get the material connected to the surface shader
            sShader.connectedTo(materials, true, false);
            var materialsObjects = new MObjectArray();

            if (materials.Count <= 0)
            {
                return(materialsObjects);
            }
            // if we found a material
            foreach (var plug in materials)
            {
                materialsObjects.Add(plug.node);
            }
            return(materialsObjects);
        }
Beispiel #19
0
        public static void RemoveUnusedTextures(MSelectionList list)
        {
            if (list == null)
            {
                Debug.Log("list null");
                return;
            }
            List <MObject> deleteList = new List <MObject>();

            for (int i = 0; i < list.length; i++)
            {
                MObject mo = new MObject();
                list.getDependNode((uint)i, mo);
                MFnDependencyNode imageNode     = new MFnDependencyNode(mo);
                MPlug             texOutputPlug = imageNode.findPlug(ConstantValue.plugName_fileTexOutputColor);
                MPlugArray        destPlugs     = new MPlugArray();
                texOutputPlug.destinations(destPlugs);
                if (destPlugs.Count == 0)
                {
                    deleteList.Add(mo);
                    Debug.Log("remove no use:" + imageNode.absoluteName);
                }
                else
                {
                    Debug.Log("still used:" + imageNode.absoluteName);
                    for (int j = 0; j < destPlugs.length; j++)
                    {
                        Debug.Log(" by:" + destPlugs[0].partialName(true));
                    }
                }
            }
            BasicFunc.DeleteObjects(deleteList);
        }
Beispiel #20
0
        public static MFnBlendShapeDeformer GetBlendShape(MObject targetObject = null)
        {
            if (targetObject == null)
            {
                targetObject = BasicFunc.GetSelectedObject(0);
            }
            MDagPath          dag_target  = MDagPath.getAPathTo(targetObject);
            MFnDependencyNode node_target = new MFnDependencyNode(targetObject);
            MPlug             plug        = node_target.findPlug("inMesh");

            Debug.Log("node_target:" + node_target.name + " plug:" + plug.name);
            MItDependencyGraph mit = new MItDependencyGraph(plug, MFn.Type.kBlendShape, MItDependencyGraph.Direction.kUpstream);

            //MDagPath dagPath = new MDagPath();
            //MItDependencyNodes mitnode = new MItDependencyNodes(MFn.Type.kBlendShape);


            while (!mit.isDone)
            {
                MObject           mo    = mit.currentItem();
                MFnDependencyNode dnode = new MFnDependencyNode(mo);
                Debug.Log("moing:" + dnode.absoluteName);
                if (mo.hasFn(MFn.Type.kBlendShape))
                {
                    Debug.Log("find blendshape");
                    return(new MFnBlendShapeDeformer(mo));
                }
                mit.next();
            }

            return(null);
        }
Beispiel #21
0
        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;
        }
Beispiel #22
0
        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;
            }
        }
Beispiel #23
0
        public static MSelectionList GetMaterialsWithTex(MFnDependencyNode imageNode, out MPlugArray texColorDestPlugs, out MPlugArray texTransparencyDestPlugs)
        {
            MPlug plug = imageNode.findPlug(ConstantValue.plugName_fileTexOutputColor);

            texColorDestPlugs = new MPlugArray();
            plug.destinations(texColorDestPlugs);
            MPlug plug_outTransparency = imageNode.findPlug(ConstantValue.plugName_fileTexOutputTransparency);

            texTransparencyDestPlugs = new MPlugArray();
            plug_outTransparency.destinations(texTransparencyDestPlugs);
            //BasicFunc.PrintPlugs(destPlugs);

            MSelectionList newSelection = new MSelectionList();

            for (int i = 0; i < texColorDestPlugs.length; i++)
            {
                newSelection.add(texColorDestPlugs[i].node);
            }
            //BasicFunc.Select(newSelection);
            return(newSelection);
        }
Beispiel #24
0
        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);
        }
Beispiel #25
0
        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);
            }
        }
Beispiel #26
0
 private void ExportCommonBabylonAttributes0(MFnDependencyNode babylonAttributesDependencyNode, BabylonMaterial babylonMaterial)
 {
     // Backface Culling
     if (babylonAttributesDependencyNode.hasAttribute("babylonBackfaceCulling"))
     {
         bool v = babylonAttributesDependencyNode.findPlug("babylonBackfaceCulling").asBool();
         RaiseVerbose($"backfaceCulling={v}", 3);
         babylonMaterial.backFaceCulling = v;
     }
     // unlit
     if (babylonAttributesDependencyNode.hasAttribute("babylonUnlit"))
     {
         bool v = babylonAttributesDependencyNode.findPlug("babylonUnlit").asBool();
         RaiseVerbose($"isUnlit={v}", 3);
         babylonMaterial.isUnlit = v;
     }
     // max light
     if (babylonAttributesDependencyNode.hasAttribute("babylonMaxSimultaneousLights"))
     {
         int v = babylonAttributesDependencyNode.findPlug("babylonMaxSimultaneousLights").asInt();
         RaiseVerbose($"maxSimultaneousLights={v}", 3);
         babylonMaterial.maxSimultaneousLights = v;
     }
 }
Beispiel #27
0
        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);
            }
        }
Beispiel #28
0
        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);
        }
Beispiel #29
0
        // 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;
        }
Beispiel #30
0
 public static void ChangeTexturesPrefix(MSelectionList list, string newFolderPath)
 {
     if (list == null)
     {
         Debug.Log("list null");
         return;
     }
     for (int i = 0; i < list.length; i++)
     {
         MObject mo = new MObject();
         list.getDependNode((uint)i, mo);
         MFnDependencyNode imageNode = new MFnDependencyNode(mo);
         MPlug             plug      = imageNode.findPlug(ConstantValue.plugName_fileTexPath);
         string            filePath  = plug.asString();
         Debug.Log("filePath:" + filePath);
         string fileName = Path.GetFileName(filePath);
         plug.setString(Path.Combine(newFolderPath, fileName));
     }
 }
Beispiel #31
0
 public static void RenameTextures(MSelectionList list)
 {
     if (list == null)
     {
         Debug.Log("list null");
         return;
     }
     for (int i = 0; i < list.length; i++)
     {
         MObject mo = new MObject();
         list.getDependNode((uint)i, mo);
         MFnDependencyNode imageNode = new MFnDependencyNode(mo);
         MPlug             plug      = imageNode.findPlug(ConstantValue.plugName_fileTexPath);
         string            filePath  = plug.asString();
         Debug.Log("filePath:" + filePath);
         string fileName = BasicFunc.GetFileName(filePath);
         Debug.Log("fileName:" + fileName);
         imageNode.setName(fileName);
     }
 }
Beispiel #32
0
 public static void RenameMaterials(MSelectionList list)
 {
     if (list == null)
     {
         Debug.Log("list null");
         return;
     }
     for (int i = 0; i < list.length; i++)
     {
         MObject mo = new MObject();
         list.getDependNode((uint)i, mo);
         MFnDependencyNode matNode    = new MFnDependencyNode(mo);
         MPlug             plug       = matNode.findPlug(ConstantValue.plugName_matColorInput);
         MPlug             sourcePlug = plug.source;
         if (sourcePlug != null)
         {
             MFnDependencyNode sourceNode = new MFnDependencyNode(sourcePlug.node);
             matNode.setName("mat_" + sourceNode.name);
         }
     }
 }
        // -------------------------
        // --------- Utils ---------
        // -------------------------

        private string getSourcePathFromFileTexture(MFnDependencyNode textureDependencyNode)
        {
            MObject sourceObject = textureDependencyNode.objectProperty;

            // Retreive texture file path
            if (!sourceObject.hasFn(MFn.Type.kFileTexture))
            {
                RaiseError("Only file texture is supported.", logRankTexture + 1);
                return(null);
            }
            MPlug fileTextureNamePlug = textureDependencyNode.findPlug("fileTextureName");

            if (fileTextureNamePlug == null || fileTextureNamePlug.isNull)
            {
                RaiseError("Texture path is missing.", logRankTexture + 1);
                return(null);
            }
            string sourcePath = fileTextureNamePlug.asString();

            return(sourcePath);
        }
Beispiel #34
0
		public override void connectNodeToAttr(MObject sourceNode, MPlug destinationPlug, bool force)
		//
		//	Description:
		//		Overloaded function from MPxDragAndDropBehavior
		//	this method will assign the correct output from the slope shader 
		//	onto the given attribute.
		//
		{
			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);
			}
		}
Beispiel #35
0
		// 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;
		}
        public Material MakeMaterial(MFnMesh fnMesh)
        {
            MaterialGroup matGroup =new MaterialGroup () ;

            MObjectArray shaders =new MObjectArray() ;
            MIntArray indices =new MIntArray () ;
            fnMesh.getConnectedShaders (0, shaders, indices) ;
            for ( int i =0 ; i < shaders.length ; i++ ) {
                MFnDependencyNode shaderGroup =new MFnDependencyNode (shaders [i]) ;
                MPlug shaderPlug =shaderGroup.findPlug ("surfaceShader") ;
                MPlugArray connections =new MPlugArray () ;
                shaderPlug.connectedTo (connections, true, false) ;
                for ( int u =0 ; u < connections.length ; u++ ) {
                    MFnDependencyNode depNode =new MFnDependencyNode (connections [u].node) ;

                    //MPlug colorPlug =depNode.findPlug ("color") ;
                    //MColor mcolor =new MColor () ;
                    ///*MPlugArray cc =new MPlugArray () ;
                    //colorPlug.connectedTo (cc, true , false) ;
                    //if ( cc.length > 0 ) {
                    //    // Plug is driven by an input connection.
                    //    for ( int v =0 ; v < cc.length ; v++ ) {
                    //        MPlug color2Plug =cc [v] ;
                    //        Console.WriteLine (color2Plug.numChildren) ;
                    //        color2Plug.child (0).getValue (mcolor.r) ;
                    //        color2Plug.child (1).getValue (mcolor.g) ;
                    //        color2Plug.child (2).getValue (mcolor.b) ;
                    //        //color2Plug.child (3).getValue (mcolor.a) ;
                    //    }
                    //} else {*/
                    //    mcolor.r =colorPlug.child (0).asFloat () ;
                    //    mcolor.g =colorPlug.child (1).asFloat () ;
                    //    mcolor.b =colorPlug.child (2).asFloat () ;
                    //    //colorPlug.child (3).getValue (mcolor.a) ;
                    ////}

                    //MPlug trPlug =depNode.findPlug ("transparency") ;
                    //float transparency =1.0f - trPlug.child (0).asFloat () ;
                    ////return new DiffuseMaterial (new SolidColorBrush (Color.FromScRgb (transparency, mcolor.r, mcolor.g, mcolor.b))) ;

                    //DiffuseMaterial diffuse =new DiffuseMaterial (new SolidColorBrush (Color.FromScRgb (transparency, mcolor.r, mcolor.g, mcolor.b))) ;
                    //colorPlug =depNode.findPlug ("ambientColor") ;
                    //mcolor.r =colorPlug.child (0).asFloat () ;
                    //mcolor.g =colorPlug.child (1).asFloat () ;
                    //mcolor.b =colorPlug.child (2).asFloat () ;
                    //diffuse.AmbientColor =Color.FromScRgb (transparency, mcolor.r, mcolor.g, mcolor.b) ;
                    //matGroup.Children.Add (diffuse) ;

                    //colorPlug =depNode.findPlug ("specularColor") ;
                    //mcolor.r =colorPlug.child (0).asFloat () ;
                    //mcolor.g =colorPlug.child (1).asFloat () ;
                    //mcolor.b =colorPlug.child (2).asFloat () ;
                    //MPlug powerPlug =depNode.findPlug ("cosinePower") ;

                    //SpecularMaterial specular =new SpecularMaterial (new SolidColorBrush (Color.FromScRgb (1.0f, mcolor.r, mcolor.g, mcolor.b)), powerPlug.asDouble ()) ;
                    //matGroup.Children.Add (specular) ;

                    //EmissiveMaterial emissive =new EmissiveMaterial () ;
                    //matGroup.Children.Add (emissive) ;

                    try {
                        MFnLambertShader lambert =new MFnLambertShader (connections [u].node) ;

                        SolidColorBrush brush =new SolidColorBrush (Color.FromScRgb (1.0f - lambert.transparency.r, lambert.color.r, lambert.color.g, lambert.color.b)) ;
                        brush.Opacity =1.0f - lambert.transparency.r ;
                        DiffuseMaterial diffuse =new DiffuseMaterial (brush) ;
                        diffuse.AmbientColor =Color.FromScRgb (1.0f - lambert.ambientColor.a, lambert.ambientColor.r, lambert.ambientColor.g, lambert.ambientColor.b) ;
                        // no more attributes
                        matGroup.Children.Add (diffuse) ;

                        // No specular color

                        EmissiveMaterial emissive =new EmissiveMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - lambert.incandescence.a, lambert.incandescence.r, lambert.incandescence.g, lambert.incandescence.b))) ;
                        // no more attributes
                        matGroup.Children.Add (emissive) ;
                    } catch {
                    }

                    //try {
                    //    MFnReflectShader reflect =new MFnReflectShader (connections [u].node) ;

                    //    SpecularMaterial specular =new SpecularMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - reflect.specularColor.a, reflect.specularColor.r, reflect.specularColor.g, reflect.specularColor.b)), reflect.cosPower) ;
                    //    // no more attributes
                    //    matGroup.Children.Add (specular) ;
                    //} catch {
                    //}

                    try {
                        MFnPhongShader phong =new MFnPhongShader (connections [u].node) ;

                        //See Lambert
                        //SolidColorBrush brush =new SolidColorBrush (Color.FromScRgb (1.0f - phong.transparency.r, phong.color.r, phong.color.g, phong.color.b)) ;
                        //brush.Opacity =1.0f - phong.transparency.r ;
                        //DiffuseMaterial diffuse =new DiffuseMaterial (brush) ;
                        //diffuse.AmbientColor =Color.FromScRgb (1.0f - phong.ambientColor.a, phong.ambientColor.r, phong.ambientColor.g, phong.ambientColor.b) ;
                        //// no more attributes
                        //matGroup.Children.Add (diffuse) ;

                        SpecularMaterial specular =new SpecularMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - phong.specularColor.a, phong.specularColor.r, phong.specularColor.g, phong.specularColor.b)), phong.cosPower) ;
                        // no more attributes
                        matGroup.Children.Add (specular) ;

                        //See Lambert
                        //EmissiveMaterial emissive =new EmissiveMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - phong.incandescence.a, phong.incandescence.r, phong.incandescence.g, phong.incandescence.b))) ;
                        //// no more attributes
                        //matGroup.Children.Add (emissive) ;
                    } catch {
                    }

                    // todo
                    //try {
                    //    MFnBlinnShader phong =new MFnBlinnShader (connections [u].node) ;

                    //    //See Lambert
                    //    //SolidColorBrush brush =new SolidColorBrush (Color.FromScRgb (1.0f - phong.transparency.r, phong.color.r, phong.color.g, phong.color.b)) ;
                    //    //brush.Opacity =1.0f - phong.transparency.r ;
                    //    //DiffuseMaterial diffuse =new DiffuseMaterial (brush) ;
                    //    //diffuse.AmbientColor = Color.FromScRgb (1.0f - phong.ambientColor.a, phong.ambientColor.r, phong.ambientColor.g, phong.ambientColor.b) ;
                    //    //// no more attributes
                    //    //matGroup.Children.Add (diffuse) ;

                    //    //See Lambert
                    //    //EmissiveMaterial emissive =new EmissiveMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - phong.incandescence.a, phong.incandescence.r, phong.incandescence.g, phong.incandescence.b))) ;
                    //    //// no more attributes
                    //    //matGroup.Children.Add (emissive) ;
                    //} catch {
                    //}
                }
            }

            // Default to Blue
            if ( matGroup.Children.Count == 0 )
                 matGroup.Children.Add (new DiffuseMaterial (new SolidColorBrush (Color.FromRgb (0, 0, 255)))) ;
            return (matGroup) ;
        }
Beispiel #37
0
        //
        //    Description:
        //        Given the material MObject this method will
        //    return the shading group that it is assigned to.
        //    if there is no shading group associated with
        //    the material than a null MObject is apssed back.
        //
        public MObject findShadingEngine(MObject node)
        {
            MFnDependencyNode nodeFn = new MFnDependencyNode(node);
            MPlug srcPlug = nodeFn.findPlug("outColor");
            MPlugArray nodeConnections = new MPlugArray();
            srcPlug.connectedTo(nodeConnections, false, true);
            //loop through the connections
            //and find the shading engine node that
            //it is connected to
            //
            for(int i = 0; i < nodeConnections.length; i++)
            {
                if(nodeConnections[i].node.hasFn(MFn.Type.kShadingEngine))
                    return nodeConnections[i].node;
            }

            //no shading engine associated so return a
            //null MObject
            //
            return new MObject();
        }
Beispiel #38
0
        //
        //    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;
        }
Beispiel #39
0
		public MObject findShadingEngine(MObject node)
		//
		//	Description:
		//		Given the material MObject this method will
		//	return the shading group that it is assigned to.
		//	if there is no shading group associated with
		//	the material than a null MObject is apssed back.
		//
		{
			MFnDependencyNode nodeFn = new MFnDependencyNode(node);
			MPlug srcPlug = nodeFn.findPlug("outColor");
			MPlugArray nodeConnections = new MPlugArray();
			srcPlug.connectedTo(nodeConnections, false, true);
			//loop through the connections
			//and find the shading engine node that
			//it is connected to
			//
			for(int i = 0; i < nodeConnections.length; i++)
			{
				if(nodeConnections[i].node.hasFn(MFn.Type.kShadingEngine))
					return nodeConnections[i].node;
			}

			//no shading engine associated so return a
			//null MObject
			//
			return new MObject();
		}
Beispiel #40
0
        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)
            {

            }

        }
Beispiel #41
0
		//! 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;
		}
 // 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;
 }