public static MDagPath CreateJoint(string jtName)
        {
            MFnIkJoint joint    = new MFnIkJoint();
            MObject    jtObject = joint.create();

            return(MDagPath.getAPathTo(jtObject));
        }
Exemple #2
0
        public static MFnBlendShapeDeformer GetBlendShape(MObject targetObject = null)
        {
            if (targetObject == null)
            {
                targetObject = BasicFunc.GetSelectedObject(0);
            }
            MDagPath          dag_target  = MDagPath.getAPathTo(targetObject);
            MFnDependencyNode node_target = new MFnDependencyNode(targetObject);
            MPlug             plug        = node_target.findPlug("inMesh");

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

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


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

            return(null);
        }
Exemple #3
0
        /// <summary>
        /// Get for each vertex the weights for all influence objects, including zero weights.
        /// </summary>
        /// <param name="vertexWeights"></param>
        /// <param name="influenceObjects"></param>
        /// <param name="meshPath"></param>
        private static void GetMeshWeightData(List <MDoubleArray> vertexWeights, MDagPathArray influenceObjects, MDagPath meshPath)
        {
            var fnMesh = new MFnMesh(meshPath);

            // Get any attached skin cluster
            var hasSkinCluster = false;

            // Search the skin cluster affecting this geometry
            var kDepNodeIt = new MItDependencyNodes(MFn.Type.kSkinClusterFilter);

            // Go through each skin cluster in the scene until we find the one connected to this mesh
            while (!kDepNodeIt.isDone && !hasSkinCluster)
            {
                MGlobal.displayInfo("Processing skin cluster...");
                var kObject         = kDepNodeIt.thisNode;
                var kSkinClusterFn  = new MFnSkinCluster(kObject);
                var uiNumGeometries = kSkinClusterFn.numOutputConnections;
                kSkinClusterFn.influenceObjects(influenceObjects);
                MGlobal.displayInfo("\t uiNumGeometries : " + uiNumGeometries);
                MGlobal.displayInfo("\t influenceOBjects number : " + influenceObjects.Count);

                // Go through each connection on the skin cluster until we get the one connecting to this mesh
                MGlobal.displayInfo("Mesh we are looking for : " + fnMesh.fullPathName);
                for (uint uiGeometry = 0; uiGeometry < uiNumGeometries && !hasSkinCluster; uiGeometry++)
                {
                    var uiIndex       = kSkinClusterFn.indexForOutputConnection(uiGeometry);
                    var kInputObject  = kSkinClusterFn.inputShapeAtIndex(uiIndex);
                    var kOutputObject = kSkinClusterFn.outputShapeAtIndex(uiIndex);
                    if (!kOutputObject.hasFn(MFn.Type.kMesh))
                    {
                        continue;
                    }
                    var fnOutput = new MFnMesh(MDagPath.getAPathTo(kOutputObject));
                    MGlobal.displayInfo("Output object : " + fnOutput.fullPathName);

                    if (fnOutput.fullPathName != fnMesh.fullPathName)
                    {
                        continue;
                    }

                    hasSkinCluster = true;
                    MGlobal.displayInfo("\t==> A connected skin cluster has been found.");

                    // Go through each vertex (== each component) and save the weights for each one
                    var kGeometryIt = new MItGeometry(kInputObject);
                    while (!kGeometryIt.isDone)
                    {
                        var  kComponent      = kGeometryIt.currentItem;
                        var  kWeightArray    = new MDoubleArray();
                        uint uiNumInfluences = 0;
                        kSkinClusterFn.getWeights(meshPath, kComponent, kWeightArray, ref uiNumInfluences);
                        vertexWeights.Add(kWeightArray);

                        kGeometryIt.next();
                    }
                }
                kDepNodeIt.next();
            }
        }
 public static bool SetJointLimit(MObject mobject, JointType jointType)
 {
     if (mobject.hasFn(MFn.Type.kTransform))
     {
         return(SetJointLimit(new MFnTransform(MDagPath.getAPathTo(mobject)), jointType));
     }
     else
     {
         return(false);
     }
 }
Exemple #5
0
 public static MDagPath AddChildCircle(MObject targetObject)
 {
     if (targetObject.hasFn(MFn.Type.kTransform))
     {
         return(AddChildCircle(MDagPath.getAPathTo(targetObject)));
     }
     else
     {
         return(null);
     }
 }
        public static MDagPath DuplicateMesh(MDagPath targetDag)
        {
            if (targetDag == null)
            {
                return(null);
            }
            MFnMesh newMesh = new MFnMesh();

            targetDag.extendToShape();
            return(MDagPath.getAPathTo(newMesh.copy(targetDag.node)));
        }
Exemple #7
0
 public static MDagPath AddParentCircle(MObject targetObject, bool createParallelGrp)
 {
     if (targetObject.hasFn(MFn.Type.kTransform))
     {
         return(AddParentCircle(MDagPath.getAPathTo(targetObject), createParallelGrp));
     }
     else
     {
         return(null);
     }
 }
        public static void BeautifulPole(MDagPath middleDag = null, bool clearFlag_x = true, bool clearFlag_y = true, bool clearFlag_z = true, bool useMoveSkinJointsTool = true)
        {
            if (middleDag == null || middleDag.node.isNull)
            {
                middleDag = BasicFunc.GetSelectedDagPath(0);
                if (middleDag == null || middleDag.node.isNull)
                {
                    Debug.Log("please select middle joint");
                    return;
                }
            }

            MFnTransform middleTrans = new MFnTransform(middleDag);

            if (middleTrans.parentCount == 0 || middleTrans.childCount == 0)
            {
                return;
            }
            MDagPath     parentDag      = MDagPath.getAPathTo(middleTrans.parent(0));
            MDagPath     childDag       = MDagPath.getAPathTo(middleTrans.child(0));
            MFnTransform parentTrans    = new MFnTransform(parentDag);
            MFnTransform childTrans     = new MFnTransform(childDag);
            MVector      parentWorldPos = parentTrans.getTranslation(MSpace.Space.kWorld);
            MVector      middleWorldPos = middleTrans.getTranslation(MSpace.Space.kWorld);
            MVector      childWorldPos  = childTrans.getTranslation(MSpace.Space.kWorld);
            //MVector vec_middleToParent = parentWorldPos - middleWorldPos;
            //MVector vec_childToMiddle = middleWorldPos - childWorldPos;
            //MVector verticalBack = BasicFunc.Cross(vec_middleToParent, vec_childToMiddle);

            float   length0     = (float)(middleWorldPos - parentWorldPos).length;
            float   length1     = (float)(middleWorldPos - childWorldPos).length;
            MVector posByWeight = BasicFunc.Lerp(parentWorldPos, childWorldPos, length0 / (length0 + length1));

            if (useMoveSkinJointsTool)
            {
                MoveSkinJointsTool(middleDag);
            }
            //middleTrans.setTranslation(posByWeight, MSpace.Space.kWorld);
            if (!clearFlag_x)
            {
                posByWeight.x = middleWorldPos.x;
            }
            if (!clearFlag_y)
            {
                posByWeight.y = middleWorldPos.y;
            }
            if (!clearFlag_z)
            {
                posByWeight.z = middleWorldPos.z;
            }
            middleTrans.setTranslation(posByWeight, MSpace.Space.kWorld);
            childTrans.setTranslation(childWorldPos, MSpace.Space.kWorld);
            //MFnIkJoint middleJoint = new MFnIkJoint(middleDag);
        }
Exemple #9
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);
        }
Exemple #10
0
 private static void AddChildrenToList(List <MDagPath> dagList, MFnTransform rootTrans, MFn.Type filterType = MFn.Type.kInvalid)
 {
     if (filterType == MFn.Type.kInvalid || rootTrans.dagPath.hasFn(filterType))
     {
         dagList.Add(rootTrans.dagPath);
     }
     if (rootTrans.childCount > 0)
     {
         for (int i = 0; i < rootTrans.childCount; i++)
         {
             MObject  mo  = rootTrans.child((uint)i);
             MDagPath dag = MDagPath.getAPathTo(mo);
             AddChildrenToList(dagList, new MFnTransform(dag), filterType);
         }
     }
 }
Exemple #11
0
        // Node added to model callback.
        private static void userNodeAddedCB(object sender, MNodeFunctionArgs args)
        {
            MObject node = args.node;

            if (!node.isNull)
            {
                MDagPath path = new MDagPath();
                try
                {
                    MDagPath.getAPathTo(node, path);
                    string info = "DAG Model -  Node added: ";
                    info += path.fullPathName;

                    try
                    {
                        MObject obj = path.transform;
                    }
                    catch (ArgumentException)
                    {
                        info += "(WORLD)";
                    }
                    catch (Exception)
                    {
                    }

                    MGlobal.displayInfo(info);
                }
                catch (System.Exception)
                {
                    MGlobal.displayInfo("Error: failed to get dag path to node.");
                }
            }

            // remove the callback
            node.NodeAddedToModel -= userNodeAddedCB;

            // listen for removal message
            try
            {
                node.NodeRemovedFromModel += userNodeRemovedCB;
            }
            catch (System.Exception)
            {
                MGlobal.displayError("Failed to install node removed from model callback.\n");
            }
        }
Exemple #12
0
        public static MDagPath CreateCurve(MPointArray points, string curveName, int degree = 1, MFnNurbsCurve.Form form = MFnNurbsCurve.Form.kOpen)
        {
            MDoubleArray indices = new MDoubleArray();

            for (int i = 0; i < points.Count; i++)
            {
                indices.Add(i);
            }

            MFnNurbsCurve     nc           = new MFnNurbsCurve();
            MObject           curveObject  = nc.create(points, indices, (uint)degree, form, false, false);
            MDagPath          curveDagPath = MDagPath.getAPathTo(curveObject);
            MFnDependencyNode dn           = new MFnDependencyNode(curveObject);

            dn.setName(curveName);
            return(curveDagPath);
        }
Exemple #13
0
        public static MDagPath AddRPIKPole(MDagPath middleDagPath = null)
        {
            if (middleDagPath == null)
            {
                middleDagPath = BasicFunc.GetSelectedDagPath(0);
                if (middleDagPath == null)
                {
                    Debug.Log("please select middle joint");
                    return(null);
                }
            }

            MDagPath   rootDagPath = new MDagPath(), endDagPath = new MDagPath();
            MFnIkJoint middleJoint = new MFnIkJoint(middleDagPath);

            if (middleJoint.parentCount > 0)
            {
                MDagPath.getAPathTo(middleJoint.parent(0), rootDagPath);
                MFnIkJoint rootJoint = new MFnIkJoint(rootDagPath);
                if (middleJoint.childCount > 0)
                {
                    MDagPath.getAPathTo(middleJoint.child(0), endDagPath);
                    MFnIkJoint endJoint  = new MFnIkJoint(endDagPath);
                    MVector    rootPos   = rootJoint.getTranslation(MSpace.Space.kWorld);
                    MVector    middlePos = middleJoint.getTranslation(MSpace.Space.kWorld);
                    MVector    endPos    = endJoint.getTranslation(MSpace.Space.kWorld);


                    //double len0 = (middlePos - rootPos).length;
                    //double len1 = (endPos - middlePos).length;

                    MVector fitLinePos            = (rootPos + endPos) * 0.5;
                    MVector direct_pole           = middlePos - fitLinePos;
                    MVector direct_fitLine        = rootPos - endPos;
                    MVector direct_projectPolePos = BasicFunc.VerticalProject(direct_pole, direct_fitLine).normal;

                    //MVector nmPos = (rootPos * len0 + endPos * len1) * (1 / (len0 + len1));
                    float   factor  = (float)((rootPos - endPos).length / 3);
                    MVector polePos = factor * direct_projectPolePos + middlePos;

                    string locName = "loc_" + rootJoint.name + "_" + endJoint.name;
                    return(BasicFunc.CreateLocator(polePos, locName));
                }
            }
            return(null);
        }
Exemple #14
0
        public static bool BindFinger(MDagPath rootJointDagPath, string fingerTag, bool useIK = false)
        {
            MFnIkJoint rootJoint = new MFnIkJoint(rootJointDagPath);

            if (rootJoint.childCount > 0)
            {
                MObject    middleJointObject  = rootJoint.child(0);
                MDagPath   middleJointDagPath = MDagPath.getAPathTo(middleJointObject);
                MFnIkJoint middleJoint        = new MFnIkJoint(middleJointObject);
                if (middleJoint.childCount > 0)
                {
                    MObject  finalJointObject  = middleJoint.child(0);
                    MDagPath finalJointDagPath = MDagPath.getAPathTo(finalJointObject);
                    //MFnIkJoint finalJoint(finalJointObject);
                    //enough, start control
                    return(BindFinger(rootJointDagPath, middleJointDagPath, finalJointDagPath, fingerTag, useIK));
                }
            }
            return(true);
        }
Exemple #15
0
        public static List <MFnTransform> GetHierachyChainTrans(MDagPath startDag, MFn.Type filterType = MFn.Type.kInvalid, MDagPath endDag = null)
        {
            MFnTransform currentTrans = new MFnTransform(startDag);
            //no need for trans data , so mfntransform(mobject) is used
            List <MFnTransform> result = new List <MFnTransform>();

            result.Add(currentTrans);
            while (currentTrans.childCount > 0)
            {
                MObject filteredMO = new MObject();
                if (filterType != MFn.Type.kInvalid)
                {
                    bool filterOK = false;
                    for (int i = 0; i < currentTrans.childCount; i++)
                    {
                        filteredMO = currentTrans.child((uint)i);
                        if (filteredMO.hasFn(filterType))
                        {
                            filterOK = true;
                            break;
                        }
                    }
                    if (!filterOK)
                    {
                        break;
                    }
                }
                else
                {
                    filteredMO = currentTrans.child(0);
                }
                MDagPath dag = MDagPath.getAPathTo(filteredMO);
                currentTrans = new MFnTransform(dag);
                result.Add(currentTrans);
                if (endDag != null && dag.fullPathName == endDag.fullPathName)
                {
                    break;
                }
            }
            return(result);
        }
Exemple #16
0
        public static MDagPath[] BindIKControl(MDagPath rootDagPath, MDagPath endDagPath, JointProcess.IKSolverType iKSolverType = JointProcess.IKSolverType.RotatePlane, MDagPath ctlDagPath = null)
        {
            MFnTransform endTrans      = new MFnTransform(endDagPath);
            MDagPath     middleDagPath = MDagPath.getAPathTo(endTrans.parent(0));

            if (ctlDagPath == null)
            {
                ctlDagPath = BasicFunc.AddChildCircle(endDagPath);
                BasicFunc.UnparentTransform(ctlDagPath);
                BasicFunc.FreezeTransform(new MFnTransform(ctlDagPath));
            }


            //string resultStr = MGlobal.executeCommandStringResult("ikHandle -sj " + rootObject.fullPathName() + " -ee " + endObject.fullPathName() + " -sol ikRPsolver -n ik_" + rootObject.partialPathName() + "_" + endObject.partialPathName(),true);
            //string resultStr = MGlobal.executePythonCommandStringResult("cmds.ikHandle(sj='" + rootDagPath.fullPathName + "',ee='" + endDagPath.fullPathName + "',sol='ikRPsolver',n='ik_" + rootDagPath.partialPathName + "_" + endDagPath.partialPathName + "')");

            //[u'ik_joint1_joint4', u'effector1']
            string[] resultArr = JointProcess.AddIKHandle(rootDagPath, endDagPath, iKSolverType, ctlDagPath.fullPathName);
            MGlobal.executeCommandStringResult("pointConstraint " + ctlDagPath.fullPathName + " " + resultArr[0]);

            if (iKSolverType == JointProcess.IKSolverType.RotatePlane)
            {
                MDagPath locDagPath = AddRPIKPole(middleDagPath);
                if (locDagPath != null)
                {
                    BasicFunc.FreezeTransform(new MFnTransform(locDagPath));
                    //begin to add constriant
                    BasicFunc.AddConstraint(locDagPath.fullPathName, resultArr[0], ConstantValue.ConstraintType.PoleVector);
                    //string poleConstraintResult = MGlobal.executeCommandStringResult("poleVectorConstraint " + locDagPath.fullPathName + " " + resultArr[0]);
                    //Debug.Log(poleConstraintResult);
                    return(new MDagPath[3] {
                        BasicFunc.GetDagPathByName(resultArr[0]), ctlDagPath, locDagPath
                    });
                }
            }

            return(new MDagPath[2] {
                BasicFunc.GetDagPathByName(resultArr[0]), ctlDagPath
            });
        }
Exemple #17
0
        public static List <MDagPath> AddBonesCTL(MSelectionList jointList = null, MFnTransform parentTrans = null)
        {
            if (jointList == null)
            {
                jointList = BasicFunc.GetSelectedList();
            }
            if (parentTrans == null)
            {
                parentTrans = new MFnTransform(BasicFunc.CreateEmptyGroup("grp_bonesCTL"));
            }
            if (jointList.length == 0)
            {
                return(null);
            }
            List <MDagPath> jointDags = new List <MDagPath>();

            for (int i = 0; i < jointList.length; i++)
            {
                MDagPath dag = new MDagPath();
                jointList.getDagPath((uint)i, dag);
                jointDags.Add(dag);
            }
            int count = jointDags.Count;

            MFnTransform[] jointTrans       = new MFnTransform[count];
            MFnTransform[] jointParentTrans = new MFnTransform[count];
            for (int i = 0; i < jointDags.Count; i++)
            {
                jointTrans[i]       = new MFnTransform(jointDags[i]);
                jointParentTrans[i] = new MFnTransform(MDagPath.getAPathTo(jointTrans[i].parent(0)));
            }
            MVector[] jointWorldPositions = new MVector[jointDags.Count];
            MVector   centerPos           = MVector.zero;

            for (int i = 0; i < count; i++)
            {
                jointWorldPositions[i] = jointTrans[i].getTranslation(MSpace.Space.kWorld);
                centerPos += jointWorldPositions[i];
            }
            centerPos = centerPos * (1.0f / count);

            double[] minDist_y = new double[count];
            double[] minDist_x = new double[count];

            if (count > 1)
            {
                for (int i = 0; i < count; i++)
                {
                    double closestY = double.MaxValue, closestX = double.MaxValue;
                    //int minDistIndex = 0;

                    for (int j = 0; j < count; j++)
                    {
                        if (i == j)
                        {
                            continue;
                        }
                        MVector direct = jointWorldPositions[i] - jointWorldPositions[j];
                        direct.x = Math.Abs(direct.x);
                        direct.y = Math.Abs(direct.y);
                        if (direct.x >= direct.y)
                        {
                            if (direct.x < closestX)
                            {
                                closestX = direct.x;
                                //minDistIndex = j;
                            }
                        }
                        if (direct.y >= direct.x)
                        {
                            if (direct.y < closestY)
                            {
                                closestY = direct.y;
                            }
                        }
                    }
                    minDist_y[i] = closestY;
                    minDist_x[i] = closestX;
                }
            }
            else
            {
                minDist_x[0] = 1;
                minDist_y[0] = 1;
            }


            List <MDagPath> curves = new List <MDagPath>();

            for (int i = 0; i < count; i++)
            {
                float        width = (float)minDist_x[i] / 2, height = (float)minDist_y[i] / 2;
                MDagPath     curve      = BasicFunc.CreateCTL_Square("ctl_" + jointDags[i].partialPathName, height, width);
                MFnTransform curveTrans = new MFnTransform(curve);
                BasicFunc.SetTransformParent(curveTrans, parentTrans);
                curveTrans.setTranslation(jointWorldPositions[i] - centerPos, MSpace.Space.kTransform);
                BasicFunc.FreezeTransform(curveTrans);
                BasicFunc.SetTranslateLimit(curveTrans, -width / 2, -height / 2, 0, width / 2, height / 2, 0);

                MPlug plug_curveTX = curveTrans.findPlug(ConstantValue.plugName_tx);
                MPlug plug_curveTY = curveTrans.findPlug(ConstantValue.plugName_ty);
                MPlug plug_jointRY = jointParentTrans[i].findPlug(ConstantValue.plugName_ry);
                MPlug plug_jointRZ = jointParentTrans[i].findPlug(ConstantValue.plugName_rz);
                BindAttr.ProjectPlug(plug_curveTX, plug_jointRY, -width / 2, width / 2, -45, 45);
                BindAttr.ProjectPlug(plug_curveTY, plug_jointRZ, -height / 2, height / 2, -45, 45);
                curves.Add(curve);
            }
            return(curves);
        }
Exemple #18
0
        private void doSimpleSolver()
        //
        // Solve single joint in the x-y plane
        //
        // - first it calculates the angle between the handle and the end-effector.
        // - then it determines which way to rotate the joint.
        //
        {
            // Get the handle and create a function set for it
            //
            MIkHandleGroup handle_group = handleGroup;

            if (null == handle_group)
            {
                throw new System.InvalidOperationException("invalid handle group.");
            }

            MObject     handle     = handle_group.handle(0);
            MDagPath    handlePath = MDagPath.getAPathTo(handle);
            MFnIkHandle fnHandle   = new MFnIkHandle(handlePath);

            // Get the position of the end_effector
            //
            MDagPath end_effector = new MDagPath();

            fnHandle.getEffector(end_effector);
            MFnTransform tran = new MFnTransform(end_effector);
            MPoint       effector_position = tran.rotatePivot(MSpace.Space.kWorld);

            // Get the position of the handle
            //
            MPoint handle_position = fnHandle.rotatePivot(MSpace.Space.kWorld);

            // Get the start joint position
            //
            MDagPath start_joint = new MDagPath();

            fnHandle.getStartJoint(start_joint);
            MFnTransform start_transform = new MFnTransform(start_joint);
            MPoint       start_position  = start_transform.rotatePivot(MSpace.Space.kWorld);

            // Calculate the rotation angle
            //
            MVector v1    = start_position.minus(effector_position);
            MVector v2    = start_position.minus(handle_position);
            double  angle = v1.angle(v2);

            // -------- Figure out which way to rotate --------
            //
            //  define two vectors U and V as follows
            //  U   =   EndEffector(E) - StartJoint(S)
            //  N   =   Normal to U passing through EndEffector
            //
            //  Clip handle_position to half-plane U to determine the region it
            //  lies in. Use the region to determine  the rotation direction.
            //
            //             U
            //             ^              Region      Rotation
            //             |  B
            //            (E)---N            A          C-C-W
            //         A   |                 B           C-W
            //             |  B
            //             |
            //            (S)
            //
            double rot = 0.0;                   // Rotation about Z-axis

            // U and N define a half-plane to clip the handle against
            //
            MVector U = effector_position.minus(start_position);

            U.normalize();

            // Get a normal to U
            //
            MVector zAxis = new MVector(0.0, 0.0, 1.0);
            MVector N     = U.crossProduct(zAxis);              // Cross product

            N.normalize();

            // P is the handle position vector
            //
            MVector P = handle_position.minus(effector_position);

            // Determine the rotation direction
            //
            double PdotN = P[0] * N[0] + P[1] * N[1];

            if (PdotN < 0)
            {
                // counter-clockwise
                rot = angle;
            }
            else
            {
                // clockwise
                rot = -1.0 * angle;
            }

            // get and set the Joint Angles
            //
            MDoubleArray jointAngles = new MDoubleArray();

            getJointAngles(jointAngles);
            jointAngles.set(jointAngles[0] + rot, 0);
            setJointAngles(jointAngles);
        }
Exemple #19
0
        public override void doSolve()
        {
            MIkHandleGroup handle_group = handleGroup;

            if (handle_group == null)
            {
                throw new InvalidOperationException("Invalid handle group");
            }

            MObject     handle     = handle_group.handle(0);
            MDagPath    handlePath = MDagPath.getAPathTo(handle);
            MFnIkHandle handleFn   = new MFnIkHandle(handlePath);

            //Effector
            //
            MDagPath effectorPath = new MDagPath();

            handleFn.getEffector(effectorPath);
            MFnIkEffector effectorFn = new MFnIkEffector(effectorPath);

            effectorPath.pop();
            MFnIkJoint midJoinFn = new MFnIkJoint(effectorPath);

            // Start Joint
            //
            MDagPath startJointPath = new MDagPath();

            handleFn.getStartJoint(startJointPath);
            MFnIkJoint startJointFn = new MFnIkJoint(startJointPath);

            // Preferred angles
            //
            double [] startJointPrefAngle = new double[3];
            double[]  midJointPrefAngle   = new double[3];

            startJointFn.getPreferedAngle(startJointPrefAngle);
            midJoinFn.getPreferedAngle(midJointPrefAngle);

            // Set to preferred angles
            //
            startJointFn.setRotation(startJointPrefAngle, startJointFn.rotationOrder);

            midJoinFn.setRotation(midJointPrefAngle, midJoinFn.rotationOrder);

            MPoint  handlePos   = handleFn.rotatePivot(MSpace.Space.kWorld);
            AwPoint awHandlePos = new AwPoint(handlePos.x, handlePos.y, handlePos.z, handlePos.w);

            MPoint  effectorPos   = effectorFn.rotatePivot(MSpace.Space.kWorld);
            AwPoint awEffectorPos = new AwPoint(effectorPos.x, effectorPos.y, effectorPos.z, effectorPos.w);

            MPoint  midJoinPos   = midJoinFn.rotatePivot(MSpace.Space.kWorld);
            AwPoint awMidJoinPos = new AwPoint(midJoinPos.x, midJoinPos.y, midJoinPos.z, midJoinPos.w);

            MPoint  startJointPos   = startJointFn.rotatePivot(MSpace.Space.kWorld);
            AwPoint awStartJointPos = new AwPoint(startJointPos.x, startJointPos.y, startJointPos.z, startJointPos.w);

            AwVector poleVector = poleVectorFromHandle(handlePath);
            MMatrix  m          = handlePath.exclusiveMatrix;
            AwMatrix awM        = new AwMatrix();

            awM.setMatrix(m);
            poleVector = poleVector.mulMatrix(awM);
            double twistValue = twistFromHandle(handlePath);

            AwQuaternion qStart = new AwQuaternion();
            AwQuaternion qMid   = new AwQuaternion();

            solveIK(awStartJointPos, awMidJoinPos, awEffectorPos, awHandlePos,
                    poleVector, twistValue, qStart, qMid);

            MQuaternion mid   = new MQuaternion(qMid.x, qMid.y, qMid.z, qMid.w);
            MQuaternion start = new MQuaternion(qStart.x, qStart.y, qStart.z, qStart.w);

            midJoinFn.rotateBy(mid, MSpace.Space.kWorld);
            startJointFn.rotateBy(start, MSpace.Space.kWorld);

            return;
        }
Exemple #20
0
 public static MFnTransform GetParent(MDagPath dag, int index = 0)
 {
     return(new MFnTransform(MDagPath.getAPathTo(new MFnTransform(dag).parent((uint)index))));
 }
Exemple #21
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());
        }
Exemple #22
0
        private static Dictionary <string, MayaM2Bone> ExtractJoints(List <MayaM2Sequence> seqList)
        {
            var jointMap = new Dictionary <string, MayaM2Bone>();

            //Goal of iteration : Extract raw joint data and store it in intermediate object, MayaM2Bone
            var processedJoints = new HashSet <string>();

            for (var jointIter = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kJoint); !jointIter.isDone; jointIter.next())
            {
                var jointPath = new MDagPath();
                jointIter.getPath(jointPath);
                if (processedJoints.Contains(jointPath.fullPathName))
                {
                    continue;
                }
                MGlobal.displayInfo("Extracting raw data of " + jointPath.fullPathName);
                var joint    = new MFnIkJoint(jointPath);
                var mayaBone = new MayaM2Bone();
                jointMap[jointPath.fullPathName] = mayaBone;

                // Hierarchy
                var isRoot = joint.parentCount == 0 || !joint.parent(0).hasFn(MFn.Type.kJoint);
                if (!isRoot)
                {
                    var parentPath = new MDagPath();
                    MDagPath.getAPathTo(joint.parent(0), parentPath);
                    if (!jointMap.ContainsKey(parentPath.fullPathName))
                    {
                        MGlobal.displayError("\tParent is not referenced. Crash incoming. Path : " + parentPath.fullPathName);
                    }
                    jointMap[jointPath.fullPathName].Parent = jointMap[parentPath.fullPathName];
                }
                //Note : M2Bone.submesh_id is wrong in the wiki. Do not try to compute it.
                // Label
                jointMap[jointPath.fullPathName].Type      = MGlobal.executeCommandStringResult("getAttr -asString " + joint.fullPathName + ".type");
                jointMap[jointPath.fullPathName].OtherType = MGlobal.executeCommandStringResult("getAttr -asString " + joint.fullPathName + ".otherType");
                jointMap[jointPath.fullPathName].Side      = MGlobal.executeCommandStringResult("getAttr -asString " + joint.fullPathName + ".side");

                // Base translation is used to compute position
                MAnimControl.currentTime = 0;
                jointMap[jointPath.fullPathName].BaseTranslation = joint.getTranslation(MSpace.Space.kTransform);

                foreach (var seq in seqList)
                {
                    var transData = new List <Tuple <uint, MVector> >();
                    var rotData   = new List <Tuple <uint, MQuaternion> >();
                    var scaleData = new List <Tuple <uint, MVector> >();
                    for (var i = seq.Start; i < seq.End; i += 33) //TODO FIXME What if not multiple of 33 ?
                    {
                        //Get data for this joint for this frame
                        MAnimControl.currentTime = new MTime(i, MTime.Unit.kMilliseconds);

                        var translation = joint.getTranslation(MSpace.Space.kTransform);
                        var rotation    = new MQuaternion();
                        joint.getRotation(rotation, MSpace.Space.kTransform);
                        var scaleArray = new double[3];
                        joint.getScale(scaleArray);
                        var scale = new MVector(scaleArray);

                        if (!translation.isEquivalent(MVector.zero, Epsilon))
                        {
                            var previousIsTheSame = transData.Count > 0 &&
                                                    transData.Last().Item2.isEquivalent(translation, Epsilon);
                            if (!previousIsTheSame)
                            {
                                transData.Add(new Tuple <uint, MVector>((uint)(i - seq.Start), translation));
                            }
                        }
                        if (!rotation.isEquivalent(MQuaternion.identity, Epsilon))
                        {
                            var previousIsTheSame = rotData.Count > 0 &&
                                                    rotData.Last().Item2.isEquivalent(rotation, Epsilon);
                            if (!previousIsTheSame)
                            {
                                rotData.Add(new Tuple <uint, MQuaternion>((uint)(i - seq.Start), rotation));
                            }
                        }
                        if (!scale.isEquivalent(MVector.one, Epsilon))
                        {
                            var previousIsTheSame = scaleData.Count > 0 &&
                                                    scaleData.Last().Item2.isEquivalent(scale, Epsilon);
                            if (!previousIsTheSame)
                            {
                                scaleData.Add(new Tuple <uint, MVector>((uint)(i - seq.Start), scale));
                            }
                        }
                    }
                    if (transData.Count > 0)
                    {
                        jointMap[joint.fullPathName].Translation.Add(transData);
                    }
                    if (rotData.Count > 0)
                    {
                        jointMap[joint.fullPathName].Rotation.Add(rotData);
                    }
                    if (scaleData.Count > 0)
                    {
                        jointMap[joint.fullPathName].Scale.Add(scaleData);
                    }
                }


                processedJoints.Add(jointPath.fullPathName);
            }

            //Goal of iteration : apply transformations to joint data & their children
            processedJoints.Clear();
            for (var jointIter = new MItDag(MItDag.TraversalType.kBreadthFirst, MFn.Type.kJoint);
                 !jointIter.isDone;
                 jointIter.next())
            {
                var jointPath = new MDagPath();
                jointIter.getPath(jointPath);
                if (processedJoints.Contains(jointPath.fullPathName))
                {
                    continue;
                }
                MGlobal.displayInfo("Applying joint orient of " + jointPath.fullPathName);
                var joint       = new MFnIkJoint(jointPath);
                var jointOrient = new MQuaternion();
                joint.getOrientation(jointOrient);

                for (uint i = 0; i < joint.childCount; i++)
                {
                    if (!joint.child(i).hasFn(MFn.Type.kJoint))
                    {
                        continue;
                    }
                    var childFn = new MFnIkJoint(joint.child(i));
                    MGlobal.displayInfo("\tto " + childFn.fullPathName + ";");
                    jointMap[childFn.fullPathName].RotateTranslation(jointOrient);
                }

                processedJoints.Add(jointPath.fullPathName);
            }
            return(jointMap);
        }
Exemple #23
0
        public static MFnIkJoint[] AddReverseFootBone(MDagPath rootDagPath, MDagPath middleDagPath, MDagPath endDagPath)
        {
            //啊啊
            //*reverseBones = new MDagPath[8];
            MFnIkJoint[] result = new MFnIkJoint[8];

            MFnIkJoint rootJoint = new MFnIkJoint();
            MVector    rootPos   = new MFnTransform(rootDagPath).getTranslation(MSpace.Space.kWorld);
            MVector    middlePos = new MFnTransform(middleDagPath).getTranslation(MSpace.Space.kWorld);
            MVector    endPos    = new MFnTransform(endDagPath).getTranslation(MSpace.Space.kWorld);
            //Debug.Log("root:" + BasicFunc.ToCMDSParamStr(rootPos) + " middle:" + BasicFunc.ToCMDSParamStr(middlePos) + " end:" + BasicFunc.ToCMDSParamStr(endPos));

            MObject jt_ankle_Object = rootJoint.create();

            result[0] = new MFnIkJoint(MDagPath.getAPathTo(jt_ankle_Object));
            result[0].setTranslation(rootPos, MSpace.Space.kWorld);

            MObject jt_heel_Object = rootJoint.create(jt_ankle_Object);

            result[1] = new MFnIkJoint(MDagPath.getAPathTo(jt_heel_Object));
            result[1].setTranslation(new MVector(rootPos.x, endPos.y, rootPos.z), MSpace.Space.kWorld);

            MObject jt_side_Object = rootJoint.create(jt_heel_Object);

            result[2] = new MFnIkJoint(MDagPath.getAPathTo(jt_side_Object));
            MVector footDirect   = endPos - middlePos;
            MVector middleGround = new MVector(middlePos.x, endPos.y, middlePos.z);
            MVector offset       = BasicFunc.Cross(footDirect, new MVector(0, 0.6, 0));

            offset *= Math.Sign(BasicFunc.Dot(middleGround, offset));
            //float sideFactor = (float)(0.6 * (middlePos - endPos).length / Math.Abs(middlePos.z));
            result[2].setTranslation(middleGround + offset, MSpace.Space.kWorld);

            MObject jt_front_Object = rootJoint.create(jt_side_Object);

            result[3] = new MFnIkJoint(MDagPath.getAPathTo(jt_front_Object));
            result[3].setTranslation(endPos, MSpace.Space.kWorld);

            MObject jt_middleF_Object = rootJoint.create(jt_front_Object);

            result[4] = new MFnIkJoint(MDagPath.getAPathTo(jt_middleF_Object));
            result[4].setTranslation(middlePos, MSpace.Space.kWorld);

            MObject jt_middleB_Object = rootJoint.create(jt_front_Object);

            result[5] = new MFnIkJoint(MDagPath.getAPathTo(jt_middleB_Object));
            result[5].setTranslation(middlePos, MSpace.Space.kWorld);

            MObject jt_toe_Object = rootJoint.create(jt_middleF_Object);

            result[6] = new MFnIkJoint(MDagPath.getAPathTo(jt_toe_Object));
            result[6].setTranslation(endPos, MSpace.Space.kWorld);

            MObject jt_ankleIn_Object = rootJoint.create(jt_middleB_Object);

            result[7] = new MFnIkJoint(MDagPath.getAPathTo(jt_ankleIn_Object));
            result[7].setTranslation(rootPos, MSpace.Space.kWorld);

            Debug.Log("create joints ok");

            return(result);
        }