Ejemplo n.º 1
0
        public static void BindBodySplineIK(MSelectionList jointList = null)
        {
            if (jointList == null)
            {
                jointList = BasicFunc.GetSelectedList();
            }
            //check if all of selected objects are joint
            int count = (int)jointList.length;

            if (count < 2)
            {
                return;
            }
            MDagPath dag_breastJoint = new MDagPath(), dag_hipJoint = new MDagPath();

            for (int i = 0; i < count; i++)
            {
                MDagPath jtDagPath = new MDagPath();
                jointList.getDagPath((uint)i, jtDagPath);
                if (jtDagPath != null)
                {
                    if (!jtDagPath.hasFn(MFn.Type.kJoint))
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

            jointList.getDagPath((uint)(count - 1), dag_breastJoint);
            jointList.getDagPath(0, dag_hipJoint);

            MFnIkJoint     breastJoint       = new MFnIkJoint(dag_breastJoint);
            MFnIkJoint     hipJoint          = new MFnIkJoint(dag_hipJoint);
            MDagPath       dag_curve         = JointProcess.CreateJointsCurve(jointList);
            MDagPath       dag_jtctl_breast  = JointProcess.CreateJoint(breastJoint, "jtctl_breast");
            MDagPath       dag_jtctl_hip     = JointProcess.CreateJoint(hipJoint, "jtctl_hip");
            MSelectionList bindSelectionList = new MSelectionList();

            bindSelectionList.add(dag_curve);
            bindSelectionList.add(dag_jtctl_breast);
            bindSelectionList.add(dag_jtctl_hip);
            BasicFunc.Select(bindSelectionList);

            MGlobal.executeCommand("SmoothBindSkin");
            string   ikName = JointProcess.AddIKHandle(dag_hipJoint, dag_breastJoint, JointProcess.IKSolverType.Spline, dag_curve.fullPathName)[0];
            MDagPath dag_ik = BasicFunc.GetDagPathByName(ikName);

            BasicFunc.ConnectAttr(dag_jtctl_breast.fullPathName + ".rotate.rotateY", dag_ik.fullPathName + ".twist", true, true);
        }
Ejemplo n.º 2
0
        public static MDagPath CurveToHair(ref MDagPath hairSystemDagPath, MDagPath curveDagPath = null, ConstantValue.HairPointLockType pointLock = ConstantValue.HairPointLockType.Base)
        {
            if (curveDagPath == null)
            {
                curveDagPath = BasicFunc.GetSelectedDagPath(0);
            }
            bool           hairSystemReady = !hairSystemDagPath.node.isNull;
            MSelectionList targetList      = new MSelectionList();

            targetList.add(curveDagPath);
            if (hairSystemReady)
            {
                Debug.Log("hair system ready");
                targetList.add(hairSystemDagPath);
            }
            else
            {
                Debug.Log("hair system need to be created!");
            }
            BasicFunc.Select(targetList);


            string cmdStr    = "cmds.MakeCurvesDynamic(0,0,0,1,0)";
            string resultStr = MGlobal.executePythonCommandStringResult(cmdStr);

            MDagPath result = new MDagPath();

            //Debug.Log(curveDagPath.fullPathName);
            MFnTransform curveTrans = new MFnTransform(curveDagPath);

            if (curveTrans.parentCount > 0)
            {
                MDagPath follicleDagPath = MDagPath.getAPathTo(curveTrans.parent(0));
                MGlobal.executeCommand(string.Format("setAttr {0}.pointLock {1}", follicleDagPath.fullPathName, (int)pointLock));
                if (follicleDagPath.hasFn(MFn.Type.kFollicle))
                {
                    Debug.Log("follicle exist!");
                    ConvertHairSelection(HairSelectionType.OutputCurves, follicleDagPath);
                    result = BasicFunc.GetSelectedDagPath(0);
                    new MFnDependencyNode(result.node).setName("dy_" + curveDagPath.partialPathName);
                    if (!hairSystemReady)
                    {
                        ConvertHairSelection(HairSelectionType.HairSystem);
                        hairSystemDagPath = BasicFunc.GetSelectedDagPath(0);
                        hairSystemReady   = true;
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 3
0
        public void ResetCamera()
        {
            //<PerspectiveCamera UpDirection="0,1,0" Position="1,1,1" LookDirection="-1,-1,-1" FieldOfView="45" />
            MDagPath cameraPath;

            try {
                // Try with a Maya host first
                cameraPath = M3dView.active3dView.Camera;
            } catch {
                // We are in standalone mode (WPF application)
                MSelectionList list = new MSelectionList();
                list.add("persp");
                cameraPath = new MDagPath();
                list.getDagPath(0, cameraPath);
            }

            MFnCamera fnCamera = new MFnCamera(cameraPath);
            MPoint    eyePoint = fnCamera.eyePoint(MSpace.Space.kWorld);
            MPoint    centerOfInterestPoint = fnCamera.centerOfInterestPoint(MSpace.Space.kWorld);
            MVector   direction             = centerOfInterestPoint.minus(eyePoint);
            MVector   upDirection           = fnCamera.upDirection(MSpace.Space.kWorld);

            camera.Position      = new Point3D(eyePoint.x, eyePoint.y, eyePoint.z);
            camera.LookDirection = new Vector3D(direction.x, direction.y, direction.z);
            MAngle fieldOfView = new MAngle(fnCamera.verticalFieldOfView);              //verticalFieldOfView / horizontalFieldOfView

            camera.FieldOfView       = fieldOfView.asDegrees;
            camera.UpDirection       = new Vector3D(upDirection.x, upDirection.y, upDirection.z);
            camera.NearPlaneDistance = fnCamera.nearClippingPlane;
            camera.FarPlaneDistance  = fnCamera.farClippingPlane;
            camera.Transform         = new Transform3DGroup();
            (camera.Transform as Transform3DGroup).Children.Add(new TranslateTransform3D(new Vector3D()));
        }
Ejemplo n.º 4
0
        public MSelectionList RestoreSelectionOnList(MSelectionList targetList = null, bool selectResult = false)
        {
            if (targetList == null || targetList.length == 0)
            {
                targetList = BasicFunc.GetSelectedList();
            }

            MSelectionList resultSelection = new MSelectionList();

            for (int i = 0; i < targetList.length; i++)
            {
                if (i >= selectedIndicesList.Count)
                {
                    break;
                }
                MDagPath dag = new MDagPath();
                targetList.getDagPath((uint)i, dag);
                MFnSingleIndexedComponent sic = new MFnSingleIndexedComponent();
                MObject components            = sic.create(MFn.Type.kMeshPolygonComponent);
                sic.addElements(new MIntArray(selectedIndicesList[i]));
                resultSelection.add(dag, components);
                //resultSelection.add(dag);
            }
            if (selectResult)
            {
                BasicFunc.Select(resultSelection);
            }
            return(resultSelection);
        }
Ejemplo n.º 5
0
        private static string GetParentName(MFnIkJoint Joint)
        {
            // Attempt to result
            var FullPath  = Joint.fullPathName;
            var SplitPath = FullPath.Substring(1).Split('|');

            if (SplitPath.Length > 2)
            {
                // We have parents, fetch second to last
                return(CleanNodeName(SplitPath[SplitPath.Length - 2]));
            }
            else if (SplitPath.Length == 2)
            {
                // We have parents, ensure this is a joint parent
                var SelectList = new MSelectionList();
                SelectList.add(FullPath.Substring(0, FullPath.IndexOf("|", 1)));

                // Grab it
                var Result = new MDagPath();
                SelectList.getDagPath(0, Result);

                // Check
                if (Result.hasFn(MFn.Type.kJoint))
                {
                    return(CleanNodeName(SplitPath[SplitPath.Length - 2]));
                }
            }

            // Root bone
            return(string.Empty);
        }
Ejemplo n.º 6
0
        public static void Select(MDagPath dagPath)
        {
            MSelectionList list = new MSelectionList();

            list.add(dagPath);
            Select(list);
        }
Ejemplo n.º 7
0
        void parseArgs(MArgList args)
        {
            string         arg          = "";
            MSelectionList list         = new MSelectionList();
            bool           charNameUsed = false;
            string         charName;
            const string   charFlag     = "-c";
            const string   charFlagLong = "-char";

            for (uint i = 0; i < args.length; i++)
            {
                arg = args.asString(i);
                if (arg == charFlag || arg == charFlagLong)
                {
                    // get the char name
                    //
                    if (i == args.length - 1)
                    {
                        arg += ": must specify a character name";
                        throw new ArgumentException(arg, "args");
                    }
                    i++;
                    charName = args.asString(i);
                    list.add(charName);

                    charNameUsed = true;
                }
                else
                {
                    arg += ": unknown argument";
                    throw new ArgumentException(arg, "args");
                }
            }

            if (charNameUsed)
            {
                // get the character corresponding to the node name
                //
                MItSelectionList iter = new MItSelectionList(list);
                for (; iter.isDone; iter.next())
                {
                    MObject node = new MObject();
                    iter.getDependNode(node);
                    if (node.apiType == MFn.Type.kCharacter)
                    {
                        fCharacter = node;
                        break;
                    }
                }

                if (fCharacter.isNull)
                {
                    throw new ApplicationException("Unable to get the character corresponding to the node name.");
                }
            }
        }
Ejemplo n.º 8
0
		void parseArgs(MArgList args)
		{
			string arg = "";
			MSelectionList list = new MSelectionList();
			bool charNameUsed = false;
			string charName;
			const string charFlag = "-c";
			const string charFlagLong = "-char";

			for (uint i = 0; i < args.length; i++)
			{
				arg = args.asString(i);
				if (arg == charFlag || arg == charFlagLong)
				{
					// get the char name
					//
					if (i == args.length - 1)
					{
						arg += ": must specify a character name";
						throw new ArgumentException(arg, "args"); 
					}
					i++;
					charName = args.asString(i);
					list.add(charName);

					charNameUsed = true;
				}
				else
				{
					arg += ": unknown argument";
					throw new ArgumentException(arg, "args"); 
				}
			}

			if (charNameUsed)
			{
				// get the character corresponding to the node name
				//
				MItSelectionList iter = new MItSelectionList(list);
				for (; iter.isDone; iter.next())
				{
					MObject node = new MObject();
					iter.getDependNode(node);
					if (node.apiType == MFn.Type.kCharacter)
					{
						fCharacter = node;
						break;
					}
				}

				if (fCharacter.isNull)
				{
					throw new ApplicationException("Unable to get the character corresponding to the node name.");
				}
			}
		}
Ejemplo n.º 9
0
        // get the dependency node
        MObject getDependNode(string node_name)
        {
            MSelectionList sl = new MSelectionList();

            sl.add(node_name, true);
            MObject o = new MObject();

            sl.getDependNode(0, o);
            return(o);
        }
Ejemplo n.º 10
0
        public static void Select(List <MObject> list)
        {
            MSelectionList sl = new MSelectionList();

            foreach (MObject mo in list)
            {
                sl.add(mo);
            }
            MGlobal.setActiveSelectionList(sl);
        }
Ejemplo n.º 11
0
        // get the dependency node
        private MObject getDependNode(string node_name)
        {
            var sl = new MSelectionList();

            sl.add(node_name, true);
            var o = new MObject();

            sl.getDependNode(0, o);
            return(o);
        }
Ejemplo n.º 12
0
        // get the DAG node
        public MDagPath getDagNode(string node_name)
        {
            var sl = new MSelectionList();

            sl.add(node_name, true);
            var dp = new MDagPath();

            sl.getDagPath(0, dp);
            return(dp);
        }
Ejemplo n.º 13
0
        internal static MDagPath GetObjectDagPath(MObject Object)
        {
            var SelectionList = new MSelectionList();

            SelectionList.add(new MFnDagNode(Object).fullPathName);

            var Result = new MDagPath();

            SelectionList.getDagPath(0, Result);

            return(Result);
        }
Ejemplo n.º 14
0
        // Main selection routine
        //
        public override bool select(MSelectInfo selectInfo,
                                    MSelectionList selectionList,
                                    MPointArray worldSpaceSelectPts)
        //
        // Description:
        //
        //     Main selection routine
        //
        // Arguments:
        //
        //     selectInfo           - the selection state information
        //     selectionList        - the list of selected items to add to
        //     worldSpaceSelectPts  -
        //
        {
            bool selected          = false;
            bool componentSelected = false;
            bool hilited           = false;

            hilited = (selectInfo.displayStatus == M3dView.DisplayStatus.kHilite);
            if (hilited)
            {
                componentSelected = selectVertices(selectInfo, selectionList,
                                                   worldSpaceSelectPts);
                selected = selected || componentSelected;
            }

            if (!selected)
            {
                apiMesh meshNode = (apiMesh)surfaceShape;

                // NOTE: If the geometry has an intersect routine it should
                // be called here with the selection ray to determine if the
                // the object was selected.

                selected = true;
                MSelectionMask priorityMask = new MSelectionMask(MSelectionMask.SelectionType.kSelectNurbsSurfaces);
                MSelectionList item         = new MSelectionList();
                item.add(selectInfo.selectPath);
                MPoint xformedPt = new MPoint();
                if (selectInfo.singleSelection)
                {
                    MPoint center = meshNode.boundingBox().center;
                    xformedPt = center;
                    xformedPt.multiplyEqual(selectInfo.selectPath.inclusiveMatrix);
                }

                selectInfo.addSelection(item, xformedPt, selectionList,
                                        worldSpaceSelectPts, priorityMask, false);
            }

            return(selected);
        }
Ejemplo n.º 15
0
        // Main selection routine
        //
        public override bool select(MSelectInfo selectInfo,
                                    MSelectionList selectionList,
                                    MPointArray worldSpaceSelectPts)
        {
            bool           selected          = false;
            bool           componentSelected = false;
            bool           hilited           = false;
            apiSimpleShape shapeNode         = surfaceShape as apiSimpleShape;

            if (shapeNode == null)
            {
                return(false);
            }
            hilited = (selectInfo.displayStatus == M3dView.DisplayStatus.kHilite);
            if (hilited)
            {
                componentSelected = selectVertices(selectInfo, selectionList, worldSpaceSelectPts);
                selected          = selected || componentSelected;
            }

            if (!selected)
            {
                // NOTE: If the geometry has an intersect routine it should
                // be called here with the selection ray to determine if the
                // the object was selected.

                selected = true;
                MSelectionMask priorityMask = new MSelectionMask(MSelectionMask.SelectionType.kSelectNurbsSurfaces);
                MSelectionList item         = new MSelectionList();
                item.add(selectInfo.selectPath);
                MPoint xformedPt;
                if (selectInfo.singleSelection)
                {
                    MPoint center = shapeNode.boundingBox().center;
                    xformedPt = center.multiply(selectInfo.selectPath.inclusiveMatrix);
                }
                else
                {
                    xformedPt = new MPoint();
                }

                selectInfo.addSelection(item, xformedPt, selectionList,
                                        worldSpaceSelectPts, priorityMask, false);
            }

            return(selected);
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
        /* override */
        public override bool select(MSelectInfo selectInfo,
                                    MSelectionList selectionList,
                                    MPointArray worldSpaceSelectPts)
        //
        // Select function. Gets called when the bbox for the object is selected.
        // This function just selects the object without doing any intersection tests.
        //
        {
            MSelectionMask priorityMask = new MSelectionMask(MSelectionMask.SelectionType.kSelectObjectsMask);
            MSelectionList item         = new MSelectionList();

            item.add(selectInfo.selectPath);
            MPoint xformedPt = new MPoint();

            selectInfo.addSelection(item, xformedPt, selectionList,
                                    worldSpaceSelectPts, priorityMask, false);
            return(true);
        }
Ejemplo n.º 18
0
        public static List <MDagPath> AddDynamicChainControlPerChain(MSelectionList rootJointsList = null)
        {
            if (rootJointsList == null)
            {
                rootJointsList = BasicFunc.GetSelectedList();
            }
            MDagPath        oneJoint   = new MDagPath();
            MDagPath        hairSystem = new MDagPath();
            List <MDagPath> result     = new List <MDagPath>();

            for (int i = 0; i < rootJointsList.length; i++)
            {
                rootJointsList.getDagPath((uint)i, oneJoint);
                MSelectionList tempList = new MSelectionList();
                tempList.add(oneJoint);
                AddDynamicChainControl(ref hairSystem, tempList);
            }
            return(result);
        }
Ejemplo n.º 19
0
        public MSelectionList RestoreSelectionOnDag(MDagPath targetDag = null, bool selectResult = false)
        {
            if (targetDag == null)
            {
                return(null);
            }

            MSelectionList resultSelection = new MSelectionList();

            MFnSingleIndexedComponent sic = new MFnSingleIndexedComponent();
            MObject components            = sic.create(MFn.Type.kMeshPolygonComponent);

            sic.addElements(new MIntArray(selectedIndicesList[0]));
            resultSelection.add(targetDag, components);
            //resultSelection.add(targetDag);
            if (selectResult)
            {
                BasicFunc.Select(resultSelection);
            }
            return(resultSelection);
        }
Ejemplo n.º 20
0
        private static void LoadNotetracks(ref XAnim Anim)
        {
            try
            {
                var SelectList = new MSelectionList();
                SelectList.add("SENotes");

                if (SelectList.length == 0)
                {
                    return;
                }

                // Get path
                var NotePath = new MDagPath();
                SelectList.getDagPath(0, NotePath);

                // Get node
                var Dep      = new MFnDependencyNode(NotePath.node);
                var NotePlug = Dep.findPlug("Notetracks");

                var ResultJson = "{}";
                NotePlug.getValue(out ResultJson);

                // Deserialize
                var ResultNotes = new JavaScriptSerializer().Deserialize <Dictionary <string, List <int> > >(ResultJson);

                // Append
                foreach (var Note in ResultNotes)
                {
                    foreach (var Frame in Note.Value)
                    {
                        Anim.Notetracks.Add(new Notetrack(Note.Key, Frame));
                    }
                }
            }
            catch
            {
                // Nothing..
            }
        }
Ejemplo n.º 21
0
        public void DoForMultiSelection(Action <MSelectionList> dealMethod, MSelectionList targetList = null)
        {
            if (targetList == null || targetList.length == 0)
            {
                targetList = BasicFunc.GetSelectedList();
            }

            int groupCount = selectedIndicesList.Count;

            for (int i = 0; i *groupCount < targetList.length; i++)
            {
                MSelectionList groupList = new MSelectionList();
                for (int j = 0; j < groupCount; j++)
                {
                    int      index = i * groupCount + j;
                    MDagPath dag   = new MDagPath();
                    targetList.getDagPath((uint)index, dag);
                    groupList.add(dag);
                }
                dealMethod(RestoreSelectionOnList(groupList));
            }
        }
Ejemplo n.º 22
0
 //
 // Select function. Gets called when the bbox for the object is selected.
 // This function just selects the object without doing any intersection tests.
 //
 /* override */
 public override bool select(MSelectInfo selectInfo,
     MSelectionList selectionList,
     MPointArray worldSpaceSelectPts)
 {
     MSelectionMask priorityMask = new MSelectionMask(MSelectionMask.SelectionType.kSelectObjectsMask);
     MSelectionList item = new MSelectionList();
     item.add(selectInfo.selectPath);
     MPoint xformedPt = new MPoint();
     selectInfo.addSelection(item, xformedPt, selectionList,
                              worldSpaceSelectPts, priorityMask, false);
     return true;
 }
Ejemplo n.º 23
0
        //
        // Description:
        //
        //     Vertex selection.
        //
        // Arguments:
        //
        //     selectInfo           - the selection state information
        //     selectionList        - the list of selected items to add to
        //     worldSpaceSelectPts  -
        //
        public bool selectVertices( MSelectInfo selectInfo,
            MSelectionList selectionList,
            MPointArray worldSpaceSelectPts)
        {
            bool selected = false;
            M3dView view = selectInfo.view;

            MPoint xformedPoint = new MPoint();
            MPoint selectionPoint = new MPoint();
            double z = 0.0;
            double previousZ = 0.0;
             			int closestPointVertexIndex = -1;

            MDagPath path = selectInfo.multiPath;

            // Create a component that will store the selected vertices
            //
            MFnSingleIndexedComponent fnComponent = new MFnSingleIndexedComponent();
            MObject surfaceComponent = fnComponent.create( MFn.Type.kMeshVertComponent );
            uint vertexIndex;

            // if the user did a single mouse click and we find > 1 selection
            // we will use the alignmentMatrix to find out which is the closest
            //
            MMatrix alignmentMatrix = new MMatrix();
            MPoint singlePoint = new MPoint();
            bool singleSelection = selectInfo.singleSelection;
            if( singleSelection ) {
                alignmentMatrix = selectInfo.alignmentMatrix;
            }

            // Get the geometry information
            //
            apiMesh meshNode = (apiMesh)surfaceShape;
            apiMeshGeom geom = meshNode.meshGeom();

            // Loop through all vertices of the mesh and
            // see if they lie withing the selection area
            //
            uint numVertices = geom.vertices.length;
            for ( vertexIndex=0; vertexIndex<numVertices; vertexIndex++ )
            {
                MPoint currentPoint = geom.vertices[ (int)vertexIndex ];

                // Sets OpenGL's render mode to select and stores
                // selected items in a pick buffer
                //
                view.beginSelect();

                OpenGL.glBegin(OpenGL.GL_POINTS);
                OpenGL.glVertex3f((float)currentPoint[0],
                            (float)currentPoint[1],
                            (float)currentPoint[2] );
                OpenGL.glEnd();

                if ( view.endSelect() > 0 )	// Hit count > 0
                {
                    selected = true;

                    if ( singleSelection ) {
                        xformedPoint = currentPoint;
                        xformedPoint.homogenize();
                        xformedPoint.multiplyEqual( alignmentMatrix );
                        z = xformedPoint.z;
                        if ( closestPointVertexIndex < 0 || z > previousZ ) {
                            closestPointVertexIndex = (int)vertexIndex;
                            singlePoint = currentPoint;
                            previousZ = z;
                        }
                    } else {
                        // multiple selection, store all elements
                        //
                        fnComponent.addElement( (int)vertexIndex );
                    }
                }
            }

            // If single selection, insert the closest point into the array
            //
            if ( selected && selectInfo.singleSelection ) {
                fnComponent.addElement(closestPointVertexIndex);

                // need to get world space position for this vertex
                //
                selectionPoint = singlePoint;
                selectionPoint.multiplyEqual( path.inclusiveMatrix );
            }

            // Add the selected component to the selection list
            //
            if ( selected ) {
                MSelectionList selectionItem = new MSelectionList();
                selectionItem.add( path, surfaceComponent );

                MSelectionMask mask = new MSelectionMask( MSelectionMask.SelectionType.kSelectComponentsMask );
                selectInfo.addSelection(
                    selectionItem, selectionPoint,
                    selectionList, worldSpaceSelectPts,
                    mask, true );
            }

            return selected;
        }
Ejemplo n.º 24
0
        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;
        }
Ejemplo n.º 25
0
 // get the dependency node
 MObject getDependNode(string node_name)
 {
     MSelectionList sl = new MSelectionList();
     sl.add(node_name, true);
     MObject o = new MObject();
     sl.getDependNode(0, o);
     return o;
 }
Ejemplo n.º 26
0
        public void ResetCamera()
        {
            //<PerspectiveCamera UpDirection="0,1,0" Position="1,1,1" LookDirection="-1,-1,-1" FieldOfView="45" />
            MDagPath cameraPath ;
            try {
                // Try with a Maya host first
                cameraPath =M3dView.active3dView.Camera ;
            } catch {
                // We are in standalone mode (WPF application)
                MSelectionList list =new MSelectionList () ;
                list.add ("persp") ;
                cameraPath =new MDagPath () ;
                list.getDagPath (0, cameraPath) ;
            }

            MFnCamera fnCamera =new MFnCamera (cameraPath) ;
            MPoint eyePoint =fnCamera.eyePoint (MSpace.Space.kWorld) ;
            MPoint centerOfInterestPoint =fnCamera.centerOfInterestPoint (MSpace.Space.kWorld) ;
            MVector direction =centerOfInterestPoint.minus (eyePoint) ;
            MVector upDirection =fnCamera.upDirection (MSpace.Space.kWorld) ;

            camera.Position =new Point3D (eyePoint.x, eyePoint.y, eyePoint.z) ;
            camera.LookDirection =new Vector3D (direction.x, direction.y, direction.z) ;
            MAngle fieldOfView =new MAngle (fnCamera.verticalFieldOfView) ; //verticalFieldOfView / horizontalFieldOfView
            camera.FieldOfView =fieldOfView.asDegrees ;
            camera.UpDirection =new Vector3D (upDirection.x, upDirection.y, upDirection.z) ;
            camera.NearPlaneDistance =fnCamera.nearClippingPlane ;
            camera.FarPlaneDistance =fnCamera.farClippingPlane ;
            camera.Transform =new Transform3DGroup () ;
            (camera.Transform as Transform3DGroup).Children.Add (new TranslateTransform3D (new Vector3D ())) ;
        }
Ejemplo n.º 27
0
        public static void CreateSpiderNetCurves(MSelectionList selected = null, bool convertToHair = true, bool addConstraint = true, bool bindJoints = true)
        {
            if (selected == null)
            {
                selected = BasicFunc.GetSelectedList();
            }
            List <MDagPath>        verticalCurves = new List <MDagPath>(), horizontalCurves = new List <MDagPath>();
            List <List <MVector> > colList = new List <List <MVector> >();

            List <MDagPath[]> jointPairToBind = new List <MDagPath[]>();

            int rowCount = 0;

            foreach (MDagPath dag in selected.DagPaths())
            {
                List <MFnTransform> transList  = BasicFunc.GetHierachyChainTrans(dag);
                List <MVector>      vectorList = new List <MVector>();
                if (transList.Count > rowCount)
                {
                    rowCount = transList.Count;
                }
                for (int i = 0; i < transList.Count; i++)
                {
                    vectorList.Add(transList[i].getTranslation(MSpace.Space.kWorld));
                }
                if (bindJoints)
                {
                    jointPairToBind.Add(new MDagPath[2] {
                        transList[0].dagPath, transList[transList.Count - 1].dagPath
                    });
                }
                colList.Add(vectorList);
                verticalCurves.Add(CreateLoopCircleByPos(vectorList, false, false, string.Format("netCurve_column_{0:d4}", (colList.Count - 1))));
            }
            List <List <MVector> > rowList = new List <List <MVector> >();

            for (int i = 0; i < rowCount; i++)
            {
                List <MVector> rowCircle = new List <MVector>();
                for (int j = 0; j < colList.Count; j++)
                {
                    rowCircle.Add(colList[j][i]);
                }
                rowList.Add(rowCircle);
                horizontalCurves.Add(CreateLoopCircleByPos(rowCircle, false, true, string.Format("netCurve_row_{0:d4}", (rowCircle.Count - 1))));
            }
            if (convertToHair)
            {
                MDagPath       hairSystem         = new MDagPath();
                MSelectionList listToDynamicCurve = new MSelectionList();
                Debug.Log("vertical to dynamic count:" + verticalCurves.Count);
                for (int i = 0; i < verticalCurves.Count; i++)
                {
                    listToDynamicCurve.add(verticalCurves[i]);
                }
                MDagPath[] verticalOutputCurves = CurvesToHairs(ref hairSystem, listToDynamicCurve, ConstantValue.HairPointLockType.Base);
                Debug.Log("vertical dynamic result count:" + verticalOutputCurves.Length);
                BasicFunc.RenameDagList(verticalOutputCurves, "netDyCurve_vertical_{0:d2}");
                listToDynamicCurve.clear();
                Debug.Log("horizontal to dynamic count:" + horizontalCurves.Count);
                for (int i = 0; i < horizontalCurves.Count; i++)
                {
                    listToDynamicCurve.add(horizontalCurves[i]);
                }
                MDagPath[] horizontalOutputCurves = CurvesToHairs(ref hairSystem, listToDynamicCurve, ConstantValue.HairPointLockType.None);
                Debug.Log("horizontal dynamic result count:" + horizontalOutputCurves.Length);
                BasicFunc.RenameDagList(horizontalOutputCurves, "netDyCurve_horizontal_{0:d2}");
                if (bindJoints)
                {
                    for (int i = 0; i < verticalOutputCurves.Length; i++)
                    {
                        JointProcess.AddIKHandle(jointPairToBind[i][0], jointPairToBind[i][1], JointProcess.IKSolverType.Spline, verticalOutputCurves[i].fullPathName);
                    }
                }
                if (addConstraint)
                {
                    MSelectionList outputCurveList = new MSelectionList();
                    for (int i = 0; i < verticalOutputCurves.Length; i++)
                    {
                        outputCurveList.add(verticalOutputCurves[i]);
                    }
                    for (int i = 0; i < horizontalOutputCurves.Length; i++)
                    {
                        outputCurveList.add(horizontalOutputCurves[i]);
                    }
                    AddDynamicConstraint(outputCurveList);
                }
            }
            else if (bindJoints)
            {
                for (int i = 0; i < jointPairToBind.Count; i++)
                {
                    JointProcess.AddIKHandle(jointPairToBind[i][0], jointPairToBind[i][1], JointProcess.IKSolverType.Spline, verticalCurves[i].fullPathName);
                }
            }
        }
Ejemplo n.º 28
0
 // get the DAG node
 MDagPath getDagNode(string node_name)
 {
     MSelectionList sl = new MSelectionList();
     sl.add(node_name, true);
     MDagPath dp = new MDagPath();
     sl.getDagPath(0, dp);
     return dp;
 }
Ejemplo n.º 29
0
        //
        // Description
        //
        //    Converts the given component values into a selection list of plugs.
        //    This method is used to map components to attributes.
        //
        // Arguments
        //
        //    component - the component to be translated to a plug/attribute
        //    list      - a list of plugs representing the passed in component
        //
        public override void componentToPlugs(MObject component, MSelectionList list)
        {
            if ( component.hasFn(MFn.Type.kSingleIndexedComponent) ) {

                MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent( component );
                MObject thisNode = thisMObject();
                MPlug plug = new MPlug( thisNode, mControlPoints );
                // If this node is connected to a tweak node, reset the
                // plug to point at the tweak node.
                //
                convertToTweakNodePlug(plug);

                int len = fnVtxComp.elementCount;

                for ( int i = 0; i < len; i++ )
                {
                    plug.selectAncestorLogicalIndex((uint)fnVtxComp.element(i), plug.attribute);
                    list.add(plug);
                }
            }
        }
Ejemplo n.º 30
0
		public override MatchResult matchComponent(MSelectionList item, MAttributeSpecArray spec, MSelectionList list)
		//
		// Description:
		//
		//    Component/attribute matching method.
		//    This method validates component names and indices which are
		//    specified as a string and adds the corresponding component
		//    to the passed in selection list.
		//
		//    For instance, select commands such as "select shape1.vtx[0:7]"
		//    are validated with this method and the corresponding component
		//    is added to the selection list.
		//
		// Arguments
		//
		//    item - DAG selection item for the object being matched
		//    spec - attribute specification object
		//    list - list to add components to
		//
		// Returns
		//
		//    the result of the match
		//
		{
			MatchResult result = MatchResult.kMatchOk;
			MAttributeSpec attrSpec = spec[0];
			int dim = attrSpec.dimensions;

			// Look for attributes specifications of the form :
			//     vtx[ index ]
			//     vtx[ lower:upper ]
			//
			if ( (1 == spec.length) && (dim > 0) && (attrSpec.name == "vtx") ) {
				int numVertices = (int)meshGeom().vertices.length;
				MAttributeIndex attrIndex = attrSpec[0];

				int upper = 0;
				int lower = 0;
				if ( attrIndex.hasLowerBound ) {
					attrIndex.getLower( out lower );
				}
				if ( attrIndex.hasUpperBound ) {
					attrIndex.getUpper( out upper );
				}

				// Check the attribute index range is valid
				//
				if ( (lower > upper) || (upper >= numVertices) ) {
					result = MatchResult.kMatchInvalidAttributeRange;
				}
				else {
					MDagPath path = new MDagPath();
					item.getDagPath( 0, path );
					MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent();
					MObject vtxComp = fnVtxComp.create( MFn.Type.kMeshVertComponent );

					for ( int i=lower; i<=upper; i++ )
					{
						fnVtxComp.addElement( i );
					}
					list.add( path, vtxComp );
				}
			}
			else {
				// Pass this to the parent class
				return base.matchComponent( item, spec, list );
			}

			return result;
		}
Ejemplo n.º 31
0
        override public void doIt(MArgList args)
        // Parses the given command line arguments and executes them.
        //
        {
            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;
        }
Ejemplo n.º 32
0
        public void Load(string name, SKLFile skl = null)
        {
            MIntArray        polygonIndexCounts = new MIntArray((uint)this.Indices.Count / 3);
            MIntArray        polygonIndices     = new MIntArray((uint)this.Indices.Count);
            MFloatPointArray vertices           = new MFloatPointArray((uint)this.Vertices.Count);
            MFloatArray      arrayU             = new MFloatArray((uint)this.Vertices.Count);
            MFloatArray      arrayV             = new MFloatArray((uint)this.Vertices.Count);
            MVectorArray     normals            = new MVectorArray((uint)this.Vertices.Count);
            MIntArray        normalIndices      = new MIntArray((uint)this.Vertices.Count);
            MFnMesh          mesh        = new MFnMesh();
            MDagPath         meshDagPath = new MDagPath();
            MDGModifier      modifier    = new MDGModifier();
            MFnSet           set         = new MFnSet();

            for (int i = 0; i < this.Indices.Count / 3; i++)
            {
                polygonIndexCounts[i] = 3;
            }

            for (int i = 0; i < this.Indices.Count; i++)
            {
                polygonIndices[i] = this.Indices[i];
            }

            for (int i = 0; i < this.Vertices.Count; i++)
            {
                SKNVertex vertex = this.Vertices[i];

                vertices[i]      = new MFloatPoint(vertex.Position.X, vertex.Position.Y, vertex.Position.Z);
                arrayU[i]        = vertex.UV.X;
                arrayV[i]        = 1 - vertex.UV.Y;
                normals[i]       = new MVector(vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z);
                normalIndices[i] = i;
            }

            //Assign mesh data
            mesh.create(this.Vertices.Count, this.Indices.Count / 3, vertices, polygonIndexCounts, polygonIndices, arrayU, arrayV, MObject.kNullObj);
            mesh.setVertexNormals(normals, normalIndices);
            mesh.getPath(meshDagPath);
            mesh.assignUVs(polygonIndexCounts, polygonIndices);

            //Set names
            mesh.setName(name);
            MFnTransform transformNode = new MFnTransform(mesh.parent(0));

            transformNode.setName("transform_" + name);

            //Get render partition
            MGlobal.displayInfo("SKNFile:Load - Searching for Render Partition");
            MItDependencyNodes itDependencyNodes = new MItDependencyNodes(MFn.Type.kPartition);
            MFnPartition       renderPartition   = new MFnPartition();
            bool foundRenderPartition            = false;

            for (; !itDependencyNodes.isDone; itDependencyNodes.next())
            {
                renderPartition.setObject(itDependencyNodes.thisNode);
                MGlobal.displayInfo("SKNFile:Load - Iterating through partition: " + renderPartition.name + " IsRenderPartition: " + renderPartition.isRenderPartition);
                if (renderPartition.name == "renderPartition" && renderPartition.isRenderPartition)
                {
                    MGlobal.displayInfo("SKNFile:Load - Found render partition");
                    foundRenderPartition = true;
                    break;
                }
            }


            //Create Materials
            for (int i = 0; i < this.Submeshes.Count; i++)
            {
                MFnDependencyNode dependencyNode = new MFnDependencyNode();
                MFnLambertShader  lambertShader  = new MFnLambertShader();
                SKNSubmesh        submesh        = this.Submeshes[i];
                MObject           shader         = lambertShader.create(true);

                lambertShader.setName(submesh.Name);
                lambertShader.color = MaterialProvider.GetMayaColor(i);

                MObject shadingEngine = dependencyNode.create("shadingEngine", submesh.Name + "_SG");
                MObject materialInfo  = dependencyNode.create("materialInfo", submesh.Name + "_MaterialInfo");
                if (foundRenderPartition)
                {
                    MPlug partitionPlug = new MFnDependencyNode(shadingEngine).findPlug("partition");
                    MPlug setsPlug      = MayaHelper.FindFirstNotConnectedElement(renderPartition.findPlug("sets"));
                    modifier.connect(partitionPlug, setsPlug);
                }
                else
                {
                    MGlobal.displayInfo("SKNFile:Load - Couldn't find Render Partition for mesh: " + name + "." + submesh.Name);
                }

                MPlug outColorPlug      = lambertShader.findPlug("outColor");
                MPlug surfaceShaderPlug = new MFnDependencyNode(shadingEngine).findPlug("surfaceShader");
                modifier.connect(outColorPlug, surfaceShaderPlug);

                MPlug messagePlug      = new MFnDependencyNode(shadingEngine).findPlug("message");
                MPlug shadingGroupPlug = new MFnDependencyNode(materialInfo).findPlug("shadingGroup");
                modifier.connect(messagePlug, shadingGroupPlug);

                modifier.doIt();

                MFnSingleIndexedComponent component = new MFnSingleIndexedComponent();
                MObject   faceComponent             = component.create(MFn.Type.kMeshPolygonComponent);
                MIntArray groupPolygonIndices       = new MIntArray();
                uint      endIndex = (submesh.StartIndex + submesh.IndexCount) / 3;
                for (uint j = submesh.StartIndex / 3; j < endIndex; j++)
                {
                    groupPolygonIndices.append((int)j);
                }
                component.addElements(groupPolygonIndices);

                set.setObject(shadingEngine);
                set.addMember(meshDagPath, faceComponent);
            }

            if (skl == null)
            {
                mesh.updateSurface();
            }
            else
            {
                MFnSkinCluster skinCluster             = new MFnSkinCluster();
                MSelectionList jointPathsSelectionList = new MSelectionList();

                jointPathsSelectionList.add(meshDagPath);
                for (int i = 0; i < skl.Influences.Count; i++)
                {
                    short    jointIndex = skl.Influences[i];
                    SKLJoint joint      = skl.Joints[jointIndex];
                    jointPathsSelectionList.add(skl.JointDagPaths[jointIndex]);

                    MGlobal.displayInfo(string.Format("SKNFile:Load:Bind - Added joint [{0}] {1} to binding selection", joint.ID, joint.Name));
                }

                MGlobal.selectCommand(jointPathsSelectionList);
                MGlobal.executeCommand("skinCluster -mi 4 -tsb -n skinCluster_" + name);

                MPlug      inMeshPlug        = mesh.findPlug("inMesh");
                MPlugArray inMeshConnections = new MPlugArray();
                inMeshPlug.connectedTo(inMeshConnections, true, false);

                if (inMeshConnections.length == 0)
                {
                    MGlobal.displayError("SKNFile:Load:Bind - Failed to find the created Skin Cluster");
                    throw new Exception("SKNFile:Load:Bind - Failed to find the created Skin Cluster");
                }

                MPlug         outputGeometryPlug = inMeshConnections[0];
                MDagPathArray influencesDagPaths = new MDagPathArray();

                skinCluster.setObject(outputGeometryPlug.node);
                skinCluster.influenceObjects(influencesDagPaths);

                MIntArray influenceIndices = new MIntArray((uint)skl.Influences.Count);
                for (int i = 0; i < skl.Influences.Count; i++)
                {
                    MDagPath influencePath = skl.JointDagPaths[skl.Influences[i]];

                    for (int j = 0; j < skl.Influences.Count; j++)
                    {
                        if (influencesDagPaths[j].partialPathName == influencePath.partialPathName)
                        {
                            influenceIndices[i] = j;
                            MGlobal.displayInfo("SKNReader:Load:Bind - Added Influence Joint: " + i + " -> " + j);
                            break;
                        }
                    }
                }

                MFnSingleIndexedComponent singleIndexedComponent = new MFnSingleIndexedComponent();
                MObject   vertexComponent    = singleIndexedComponent.create(MFn.Type.kMeshVertComponent);
                MIntArray groupVertexIndices = new MIntArray((uint)this.Vertices.Count);

                for (int i = 0; i < this.Vertices.Count; i++)
                {
                    groupVertexIndices[i] = i;
                }
                singleIndexedComponent.addElements(groupVertexIndices);

                MGlobal.executeCommand(string.Format("setAttr {0}.normalizeWeights 0", skinCluster.name));

                MDoubleArray weights = new MDoubleArray((uint)(this.Vertices.Count * skl.Influences.Count));
                for (int i = 0; i < this.Vertices.Count; i++)
                {
                    SKNVertex vertex = this.Vertices[i];

                    for (int j = 0; j < 4; j++)
                    {
                        double weight    = vertex.Weights[j];
                        int    influence = vertex.BoneIndices[j];

                        if (weight != 0)
                        {
                            weights[(i * skl.Influences.Count) + influence] = weight;
                        }
                    }
                }

                skinCluster.setWeights(meshDagPath, vertexComponent, influenceIndices, weights, false);
                MGlobal.executeCommand(string.Format("setAttr {0}.normalizeWeights 1", skinCluster.name));
                MGlobal.executeCommand(string.Format("skinPercent -normalize true {0} {1}", skinCluster.name, mesh.name));
                mesh.updateSurface();
            }
        }
Ejemplo n.º 33
0
		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;
		}
Ejemplo n.º 34
0
        // 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;
        }
Ejemplo n.º 35
0
        void parseArgs(MArgList args)
        {
            createdUsed   = (args.flagIndex(kCreateFlag, kCreateFlagLong) != MArgList.kInvalidArgIndex);
            editUsed      = (args.flagIndex(kEditFlag, kEditFlagLong) != MArgList.kInvalidArgIndex);
            queryUsed     = (args.flagIndex(kQueryFlag, kQueryFlagLong) != MArgList.kInvalidArgIndex);
            helpUsed      = (args.flagIndex(kHelpFlag, kHelpFlagLong) != MArgList.kInvalidArgIndex);
            numLayersUsed = (args.flagIndex(kNumLayersFlag, kNumLayersFlagLong) != MArgList.kInvalidArgIndex);

            // If flags are used which require no other information, return now.
            //
            if (createdUsed || helpUsed)
            {
                return;
            }

            uint maxArg                  = args.length - 1;
            uint activeIndex             = args.flagIndex(kActiveFlag, kActiveFlagLong);
            uint appendCameraIndex       = args.flagIndex(kAppendCameraFlag, kAppendCameraFlagLong);
            uint appendCameraAndSetIndex = args.flagIndex(kAppendCameraAndSetFlag, kAppendCameraAndSetFlagLong);
            uint cameraIndex             = args.flagIndex(kCameraFlag, kCameraFlagLong);
            uint deleteLayerIndex        = args.flagIndex(kDeleteLayerFlag, kDeleteLayerFlagLong);
            uint layerIndex              = args.flagIndex(kLayerFlag, kLayerFlagLong);
            uint layerTypeIndex          = args.flagIndex(kLayerTypeFlag, kLayerTypeFlagLong);
            uint setIndex                = args.flagIndex(kSetFlag, kSetFlagLong);

            activeUsed             = (activeIndex != MArgList.kInvalidArgIndex);
            appendCameraUsed       = (appendCameraIndex != MArgList.kInvalidArgIndex);
            appendCameraAndSetUsed = (appendCameraAndSetIndex != MArgList.kInvalidArgIndex);
            cameraUsed             = (cameraIndex != MArgList.kInvalidArgIndex);
            deleteLayerUsed        = (deleteLayerIndex != MArgList.kInvalidArgIndex);
            layerUsed     = (layerIndex != MArgList.kInvalidArgIndex);
            layerTypeUsed = (layerTypeIndex != MArgList.kInvalidArgIndex);
            setUsed       = (setIndex != MArgList.kInvalidArgIndex);

            // Process each flag.
            //
            bool maxArgUsed = false;

            if (activeUsed)
            {
                if (editUsed)
                {
                    activeVal = args.asBool((activeIndex + 1));
                    if ((layerTypeIndex + 1) == maxArg)
                    {
                        maxArgUsed = true;
                    }
                }
            }

            if (appendCameraUsed)
            {
                camName = args.asString((appendCameraIndex + 1));
                if ((appendCameraIndex + 1) == maxArg)
                {
                    maxArgUsed = true;
                }
            }

            if (appendCameraAndSetUsed)
            {
                camName = args.asString((appendCameraAndSetIndex + 1));
                setName = args.asString((appendCameraAndSetIndex + 2));
                if ((appendCameraAndSetIndex + 2) == maxArg)
                {
                    maxArgUsed = true;
                }
            }

            if (cameraUsed)
            {
                if (editUsed)
                {
                    camName = args.asString(cameraIndex + 1);
                    if ((cameraIndex + 1) == maxArg)
                    {
                        maxArgUsed = true;
                    }
                }
            }

            if (deleteLayerUsed)
            {
                cameraLayer = args.asInt(deleteLayerIndex + 1);
                if ((deleteLayerIndex + 1) == maxArg)
                {
                    maxArgUsed = true;
                }
            }

            if (layerUsed)
            {
                cameraLayer = args.asInt(layerIndex + 1);
                if ((layerIndex + 1) == maxArg)
                {
                    maxArgUsed = true;
                }
            }

            if (layerTypeUsed)
            {
                if (editUsed)
                {
                    layerTypeVal = args.asString(layerTypeIndex + 1);
                    if ((layerTypeIndex + 1) == maxArg)
                    {
                        maxArgUsed = true;
                    }
                }
            }

            if (setUsed)
            {
                if (editUsed)
                {
                    setName = args.asString(setIndex + 1);
                    if ((setIndex + 1) == maxArg)
                    {
                        maxArgUsed = true;
                    }
                }
            }


            // If all of the arguments have been used, get the cameraSet node from the selection list.
            // Otherwise, get it from the last argument.
            //
            if (maxArgUsed)
            {
                MGlobal.getActiveSelectionList(list);
            }
            else
            {
                list.add(args.asString(maxArg));
            }
        }
Ejemplo n.º 36
0
        //
        // Description:
        //
        //     Main selection routine
        //
        // Arguments:
        //
        //     selectInfo           - the selection state information
        //     selectionList        - the list of selected items to add to
        //     worldSpaceSelectPts  -
        //
        // Main selection routine
        //
        public override bool select(MSelectInfo selectInfo,
            MSelectionList selectionList,
            MPointArray worldSpaceSelectPts)
        {
            bool selected = false;
            bool componentSelected = false;
            bool hilited = false;

            hilited = (selectInfo.displayStatus == M3dView.DisplayStatus.kHilite);
            if ( hilited ) {
                componentSelected = selectVertices( selectInfo, selectionList,
                                                    worldSpaceSelectPts );
                selected = selected || componentSelected;
            }

            if ( !selected ) {

                apiMesh meshNode = (apiMesh)surfaceShape;

                // NOTE: If the geometry has an intersect routine it should
                // be called here with the selection ray to determine if the
                // the object was selected.

                selected = true;
                MSelectionMask priorityMask = new MSelectionMask( MSelectionMask.SelectionType.kSelectNurbsSurfaces );
                MSelectionList item = new MSelectionList();
                item.add( selectInfo.selectPath );
                MPoint xformedPt = new MPoint();
                if ( selectInfo.singleSelection ) {
                    MPoint center = meshNode.boundingBox().center;
                    xformedPt = center;
                    xformedPt.multiplyEqual( selectInfo.selectPath.inclusiveMatrix );
                }

                selectInfo.addSelection( item, xformedPt, selectionList,
                                         worldSpaceSelectPts, priorityMask, false );
            }

            return selected;
        }
Ejemplo n.º 37
0
 /* override */
 public override bool select(MSelectInfo selectInfo,
                              MSelectionList selectionList,
                              MPointArray worldSpaceSelectPts)
 //
 // Select function. Gets called when the bbox for the object is selected.
 // This function just selects the object without doing any intersection tests.
 //
 {
     MSelectionMask priorityMask = new MSelectionMask(MSelectionMask.SelectionType.kSelectObjectsMask);
     MSelectionList item = new MSelectionList();
     item.add(selectInfo.selectPath);
     MPoint xformedPt = new MPoint();
     selectInfo.addSelection(item, xformedPt, selectionList,
                              worldSpaceSelectPts, priorityMask, false);
     return true;
 }
Ejemplo n.º 38
0
        public bool selectVertices(MSelectInfo selectInfo,
                                   MSelectionList selectionList,
                                   MPointArray worldSpaceSelectPts)
        //
        // Description:
        //
        //     Vertex selection.
        //
        // Arguments:
        //
        //     selectInfo           - the selection state information
        //     selectionList        - the list of selected items to add to
        //     worldSpaceSelectPts  -
        //
        {
            bool    selected = false;
            M3dView view     = selectInfo.view;

            MPoint xformedPoint   = new MPoint();
            MPoint selectionPoint = new MPoint();
            double z         = 0.0;
            double previousZ = 0.0;
            int    closestPointVertexIndex = -1;

            MDagPath path = selectInfo.multiPath;

            // Create a component that will store the selected vertices
            //
            MFnSingleIndexedComponent fnComponent = new MFnSingleIndexedComponent();
            MObject surfaceComponent = fnComponent.create(MFn.Type.kMeshVertComponent);
            uint    vertexIndex;

            // if the user did a single mouse click and we find > 1 selection
            // we will use the alignmentMatrix to find out which is the closest
            //
            MMatrix alignmentMatrix = new MMatrix();
            MPoint  singlePoint     = new MPoint();
            bool    singleSelection = selectInfo.singleSelection;

            if (singleSelection)
            {
                alignmentMatrix = selectInfo.alignmentMatrix;
            }

            // Get the geometry information
            //
            apiMesh     meshNode = (apiMesh)surfaceShape;
            apiMeshGeom geom     = meshNode.meshGeom();

            // Loop through all vertices of the mesh and
            // see if they lie withing the selection area
            //
            uint numVertices = geom.vertices.length;

            for (vertexIndex = 0; vertexIndex < numVertices; vertexIndex++)
            {
                MPoint currentPoint = geom.vertices[(int)vertexIndex];

                // Sets OpenGL's render mode to select and stores
                // selected items in a pick buffer
                //
                view.beginSelect();

                OpenGL.glBegin(OpenGL.GL_POINTS);
                OpenGL.glVertex3f((float)currentPoint[0],
                                  (float)currentPoint[1],
                                  (float)currentPoint[2]);
                OpenGL.glEnd();

                if (view.endSelect() > 0)                       // Hit count > 0
                {
                    selected = true;

                    if (singleSelection)
                    {
                        xformedPoint = currentPoint;
                        xformedPoint.homogenize();
                        xformedPoint.multiplyEqual(alignmentMatrix);
                        z = xformedPoint.z;
                        if (closestPointVertexIndex < 0 || z > previousZ)
                        {
                            closestPointVertexIndex = (int)vertexIndex;
                            singlePoint             = currentPoint;
                            previousZ = z;
                        }
                    }
                    else
                    {
                        // multiple selection, store all elements
                        //
                        fnComponent.addElement((int)vertexIndex);
                    }
                }
            }

            // If single selection, insert the closest point into the array
            //
            if (selected && selectInfo.singleSelection)
            {
                fnComponent.addElement(closestPointVertexIndex);

                // need to get world space position for this vertex
                //
                selectionPoint = singlePoint;
                selectionPoint.multiplyEqual(path.inclusiveMatrix);
            }

            // Add the selected component to the selection list
            //
            if (selected)
            {
                MSelectionList selectionItem = new MSelectionList();
                selectionItem.add(path, surfaceComponent);

                MSelectionMask mask = new MSelectionMask(MSelectionMask.SelectionType.kSelectComponentsMask);
                selectInfo.addSelection(
                    selectionItem, selectionPoint,
                    selectionList, worldSpaceSelectPts,
                    mask, true);
            }

            return(selected);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// return Dynamic Output Curve
        /// </summary>
        /// <param name="hairSystemDagPath">exist hairsystem or container of created hairsystem</param>
        /// <param name="curveList"></param>
        /// <param name="pointLock">0-none, 1-base, 2-end,3-both</param>
        /// <returns></returns>
        public static MDagPath[] CurvesToHairs(ref MDagPath hairSystemDagPath, MSelectionList curveList = null, ConstantValue.HairPointLockType pointLock = ConstantValue.HairPointLockType.Base)
        {
            if (curveList == null)
            {
                curveList = BasicFunc.GetSelectedList();
            }

            bool hairSystemReady = false;

            if (!hairSystemDagPath.node.isNull)
            {
                //Debug.Log("hairSystem node is not null:" + hairSystemDagPath.fullPathName);
                curveList.add(hairSystemDagPath);
                hairSystemReady = true;
            }
            else
            {
                //Debug.Log("hairsystem node is null");
            }
            MGlobal.setActiveSelectionList(curveList);
            string cmdStr    = "cmds.MakeCurvesDynamic(0,0,0,1,0)";
            string resultStr = MGlobal.executePythonCommandStringResult(cmdStr);

            if (hairSystemReady)
            {
                //Debug.Log("remove hairSystem Selection");
                curveList.remove(curveList.length - 1);
            }
            List <MDagPath> results = new List <MDagPath>();

            for (int i = 0; i < curveList.length; i++)
            {
                MDagPath curveDagPath = new MDagPath();
                curveList.getDagPath((uint)i, curveDagPath);

                //Debug.Log(curveDagPath.fullPathName);
                MFnTransform curveTrans = new MFnTransform(curveDagPath);
                if (curveTrans.parentCount > 0)
                {
                    MDagPath follicleDagPath = MDagPath.getAPathTo(curveTrans.parent(0));
                    MGlobal.executeCommand(string.Format("setAttr {0}.pointLock {1}", follicleDagPath.fullPathName, (int)pointLock));
                    if (follicleDagPath.hasFn(MFn.Type.kFollicle))
                    {
                        Debug.Log("follicle exist!");
                        ConvertHairSelection(HairSelectionType.OutputCurves, follicleDagPath);
                        MDagPath result = BasicFunc.GetSelectedDagPath(0);
                        new MFnDependencyNode(result.node).setName("dy_" + curveDagPath.partialPathName);
                        results.Add(result);
                        if (!hairSystemReady)
                        {
                            ConvertHairSelection(HairSelectionType.HairSystem);
                            hairSystemDagPath = BasicFunc.GetSelectedDagPath(0);
                            //Debug.Log("assign hairSystem:" + hairSystemDagPath.fullPathName);
                            hairSystemReady = true;
                        }
                    }
                }
            }


            //error
            return(results.ToArray());
        }
Ejemplo n.º 40
0
        //
        // Description:
        //
        //    Component/attribute matching method.
        //    This method validates component names and indices which are
        //    specified as a string and adds the corresponding component
        //    to the passed in selection list.
        //
        //    For instance, select commands such as "select shape1.vtx[0:7]"
        //    are validated with this method and the corresponding component
        //    is added to the selection list.
        //
        // Arguments
        //
        //    item - DAG selection item for the object being matched
        //    spec - attribute specification object
        //    list - list to add components to
        //
        // Returns
        //
        //    the result of the match
        //
        public override MatchResult matchComponent(MSelectionList item, MAttributeSpecArray spec, MSelectionList list)
        {
            MatchResult result = MatchResult.kMatchOk;
            MAttributeSpec attrSpec = spec[0];
            int dim = attrSpec.dimensions;

            // Look for attributes specifications of the form :
            //     vtx[ index ]
            //     vtx[ lower:upper ]
            //
            if ( (1 == spec.length) && (dim > 0) && (attrSpec.name == "vtx") ) {
                int numVertices = (int)meshGeom().vertices.length;
                MAttributeIndex attrIndex = attrSpec[0];

                int upper = 0;
                int lower = 0;
                if ( attrIndex.hasLowerBound ) {
                    attrIndex.getLower( out lower );
                }
                if ( attrIndex.hasUpperBound ) {
                    attrIndex.getUpper( out upper );
                }

                // Check the attribute index range is valid
                //
                if ( (lower > upper) || (upper >= numVertices) ) {
                    result = MatchResult.kMatchInvalidAttributeRange;
                }
                else {
                    MDagPath path = new MDagPath();
                    item.getDagPath( 0, path );
                    MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent();
                    MObject vtxComp = fnVtxComp.create( MFn.Type.kMeshVertComponent );

                    for ( int i=lower; i<=upper; i++ )
                    {
                        fnVtxComp.addElement( i );
                    }
                    list.add( path, vtxComp );
                }
            }
            else {
                // Pass this to the parent class
                return base.matchComponent( item, spec, list );
            }

            return result;
        }
Ejemplo n.º 41
0
		public override void componentToPlugs(MObject component, MSelectionList list)
		//
		// Description
		//
		//    Converts the given component values into a selection list of plugs.
		//    This method is used to map components to attributes.
		//
		// Arguments
		//
		//    component - the component to be translated to a plug/attribute
		//    list      - a list of plugs representing the passed in component
		//
		{
			if ( component.hasFn(MFn.Type.kSingleIndexedComponent) ) {

				MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent( component );
				MObject thisNode = thisMObject();
				MPlug plug = new MPlug( thisNode, mControlPoints );
				// If this node is connected to a tweak node, reset the
				// plug to point at the tweak node.
				//
				convertToTweakNodePlug(plug);

				int len = fnVtxComp.elementCount;

				for ( int i = 0; i < len; i++ )
				{
					plug.selectAncestorLogicalIndex((uint)fnVtxComp.element(i), plug.attribute);
					list.add(plug);
				}
			}
		}