Esempio n. 1
0
        private MFnSkinCluster getMFnSkinCluster(MFnMesh mFnMesh)
        {
            MFnSkinCluster mFnSkinCluster = null;

            MPlugArray connections = new MPlugArray();

            mFnMesh.getConnections(connections);
            foreach (MPlug connection in connections)
            {
                MObject source = connection.source.node;
                if (source != null)
                {
                    if (source.hasFn(MFn.Type.kSkinClusterFilter))
                    {
                        mFnSkinCluster = new MFnSkinCluster(source);
                    }

                    if ((mFnSkinCluster == null) && (source.hasFn(MFn.Type.kSet) || source.hasFn(MFn.Type.kPolyNormalPerVertex)))
                    {
                        mFnSkinCluster = getMFnSkinCluster(source);
                    }
                }
            }

            return(mFnSkinCluster);
        }
Esempio n. 2
0
        /// <summary>
        /// Using the HasNonZeroScale function, it search for a frame where all bones have a scale higher than zero + epsilon.
        /// </summary>
        /// <param name="skin"></param>
        /// <returns>
        /// A list containing only the first valid frame. Otherwise it returns an empty list.
        /// </returns>
        private IList <double> GetValidFrames(MFnSkinCluster skin)
        {
            List <MObject> revelantNodes = GetRevelantNodes(skin);
            IList <double> validFrames   = new List <double>();
            int            start         = Loader.GetMinTime();
            int            end           = Loader.GetMaxTime();

            // For each frame:
            //  if bone scale near 0, move to the next frame
            //  else add the frame to the list and return the list
            bool   isValid      = false;
            double currentFrame = start;

            while (!isValid && currentFrame <= end)
            {
                isValid = HasNonZeroScale(revelantNodes, currentFrame);


                if (!isValid)
                {
                    currentFrame++;
                }
                else
                {
                    validFrames.Add(currentFrame);
                }
            }

            return(validFrames);
        }
Esempio n. 3
0
        /// <summary>
        /// Init the two list influentNodesBySkin and revelantNodesBySkin of a skin cluster.
        /// By getting the parents of the influent nodes.
        /// </summary>
        /// <param name="skin">the skin cluster</param>
        /// <returns>
        /// The list of nodes that form the skeleton
        /// </returns>
        private List <MObject> GetRevelantNodes(MFnSkinCluster skin)
        {
            if (revelantNodesBySkin.ContainsKey(skin))
            {
                return(revelantNodesBySkin[skin]);
            }

            List <MObject> influentNodes = GetInfluentNodes(skin);
            List <MObject> revelantNodes = new List <MObject>();


            // Add parents until it's a kWorld
            foreach (MObject node in influentNodes)
            {
                MObject currentNode = node;
                //MObject parent = findValidParent(node);   // A node can have several parents. Which one is the right one ? It seems that the first one is most likely a transform

                while (!currentNode.apiType.Equals(MFn.Type.kWorld))
                {
                    MFnDagNode dagNode = new MFnDagNode(currentNode);

                    if (revelantNodes.Count(revelantNode => Equals(revelantNode, currentNode)) == 0)
                    {
                        revelantNodes.Add(currentNode);
                    }

                    // iter
                    MObject firstParent = dagNode.parent(0);
                    currentNode = firstParent;
                }
            }
            revelantNodesBySkin.Add(skin, revelantNodes);

            return(revelantNodes);
        }
Esempio n. 4
0
        /// <summary>
        /// Init the list influentNodesBySkin of a skin cluster.
        /// By find the kjoint that are connected to the skin.
        /// </summary>
        /// <param name="skin">the skin cluster</param>
        /// <returns>
        /// The list of skin kjoint
        /// </returns>
        private List <MObject> GetInfluentNodes(MFnSkinCluster skin)
        {
            if (influentNodesBySkin.ContainsKey(skin))
            {
                return(influentNodesBySkin[skin]);
            }

            List <MObject> influentNodes = new List <MObject>();

            // Get all influenting nodes
            MPlugArray connections = new MPlugArray();

            skin.getConnections(connections);
            foreach (MPlug connection in connections)
            {
                MObject source = connection.source.node;
                if (source != null && source.hasFn(MFn.Type.kJoint))
                {
                    if (influentNodes.Count(node => Equals(node, source)) == 0)
                    {
                        influentNodes.Add(source);
                    }
                }
            }
            influentNodesBySkin.Add(skin, influentNodes);

            return(influentNodes);
        }
Esempio n. 5
0
        /// <summary>
        /// If the skin is not in the list of those that will be export, it add the skin into the list .
        /// Then it returns its index.
        /// </summary>
        /// <param name="skin">the skin to export</param>
        /// <returns>The index of the skin in the list of those that will be exported</returns>
        private int GetSkeletonIndex(MFnSkinCluster skin)
        {
            int            index         = -1;
            List <MObject> revelantNodes = GetRevelantNodes(skin);

            // Compare the revelant nodes with the list of those exported
            int currentIndex = 0;

            while (currentIndex < skins.Count && index == -1)
            {
                List <MObject> currentRevelantNodes = GetRevelantNodes(skins[currentIndex]);

                if (revelantNodes.Count == currentRevelantNodes.Count &&
                    revelantNodes.All(node1 => currentRevelantNodes.Count(node2 => Equals(node1, node2)) == 1))
                {
                    index = currentIndex;
                }

                currentIndex++;
            }

            if (index == -1)
            {
                skins.Add(skin);
                index = skins.Count - 1;
            }

            return(index);
        }
Esempio n. 6
0
        /// <summary>
        /// Find a bone in the skin cluster connections.
        /// From this bone travel the Dag up to the root node.
        /// </summary>
        /// <param name="skin">The skin cluster</param>
        /// <returns>
        /// The root node of the skeleton.
        /// </returns>
        private MObject GetRootNode(MFnSkinCluster skin)
        {
            MObject rootJoint = null;

            if (rootBySkin.ContainsKey(skin))
            {
                return(rootBySkin[skin]);
            }

            // Get a joint of the skin
            rootJoint = GetInfluentNodes(skin)[0];

            // Check the joint parent until it's a kWorld
            MFnDagNode        mFnDagNode  = new MFnDagNode(rootJoint);
            MObject           firstParent = mFnDagNode.parent(0);
            MFnDependencyNode node        = new MFnDependencyNode(firstParent);

            while (!firstParent.apiType.Equals(MFn.Type.kWorld))
            {
                rootJoint   = firstParent;
                mFnDagNode  = new MFnDagNode(rootJoint);
                firstParent = mFnDagNode.parent(0);
                node        = new MFnDependencyNode(firstParent);
            }

            rootBySkin.Add(skin, rootJoint);
            return(rootJoint);
        }
Esempio n. 7
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();
            }
        }
        /// <summary>
        /// Return the bones to export.
        /// </summary>
        /// <param name="skin">the skin to export</param>
        /// <returns>Array of BabylonBone to export</returns>
        private BabylonBone[] ExportBones(MFnSkinCluster skin)
        {
            int logRank   = 1;
            int skinIndex = GetSkeletonIndex(skin);
            List <BabylonBone>       bones = new List <BabylonBone>();
            Dictionary <string, int> indexByFullPathName = GetIndexByFullPathNameDictionary(skin);
            List <MObject>           revelantNodes       = GetRevelantNodes(skin);

            progressBoneStep = progressSkinStep / revelantNodes.Count;

            foreach (MObject node in revelantNodes)
            {
                MFnDagNode   dagNode = new MFnDagNode(node);
                MFnTransform currentNodeTransform = new MFnTransform(node);
                string       currentFullPathName  = dagNode.fullPathName;
                int          index       = indexByFullPathName[currentFullPathName];
                int          parentIndex = -1;
                string       parentId    = null;
                // find the parent node to get its index
                if (!dagNode.parent(0).hasFn(MFn.Type.kWorld))
                {
                    MFnTransform firstParentTransform = new MFnTransform(dagNode.parent(0));
                    parentId    = firstParentTransform.uuid().asString();
                    parentIndex = indexByFullPathName[firstParentTransform.fullPathName];
                }

                string boneId = currentNodeTransform.uuid().asString();
                // create the bone
                BabylonBone bone = new BabylonBone()
                {
                    id              = (!isBabylonExported)?boneId:boneId + "-bone",// the suffix "-bone" is added in babylon export format to assure the uniqueness of IDs
                    parentNodeId    = parentId,
                    name            = dagNode.name,
                    index           = indexByFullPathName[currentFullPathName],
                    parentBoneIndex = parentIndex,
                    matrix          = GetBabylonMatrix(currentNodeTransform, frameBySkeletonID[skinIndex]).m,
                    animation       = GetAnimationsFrameByFrameMatrix(currentNodeTransform)
                };

                bones.Add(bone);
                RaiseVerbose($"Bone: name={bone.name}, index={bone.index}, parentBoneIndex={bone.parentBoneIndex}, matrix={string.Join(" ", bone.matrix)}", logRank + 1);

                // Progress bar
                progressSkin += progressBoneStep;
                ReportProgressChanged(progressSkin);
                CheckCancelled();
            }

            // sort
            List <BabylonBone> sorted = new List <BabylonBone>();

            sorted = bones.OrderBy(bone => bone.index).ToList();
            bones  = sorted;

            RaiseMessage($"{bones.Count} bone(s) exported", logRank + 1);

            return(bones.ToArray());
        }
Esempio n. 9
0
        /// <summary>
        /// Return the bones to export.
        /// </summary>
        /// <param name="skin">the skin to export</param>
        /// <returns>Array of BabylonBone to export</returns>
        private BabylonBone[] ExportBones(MFnSkinCluster skin)
        {
            int logRank   = 1;
            int skinIndex = GetSkeletonIndex(skin);
            List <BabylonBone>       bones = new List <BabylonBone>();
            Dictionary <string, int> indexByFullPathName = GetIndexByFullPathNameDictionary(skin);
            List <MObject>           revelantNodes       = GetRevelantNodes(skin);

            progressBoneStep = progressSkinStep / revelantNodes.Count;

            foreach (MObject node in revelantNodes)
            {
                MFnDagNode   dagNode = new MFnDagNode(node);
                MFnTransform currentNodeTransform = new MFnTransform(node);
                string       currentFullPathName  = dagNode.fullPathName;
                int          index       = indexByFullPathName[currentFullPathName];
                int          parentIndex = -1;

                // find the parent node to get its index
                if (!dagNode.parent(0).hasFn(MFn.Type.kWorld))
                {
                    MFnTransform firstParentTransform = new MFnTransform(dagNode.parent(0));
                    parentIndex = indexByFullPathName[firstParentTransform.fullPathName];
                }

                // create the bone
                BabylonBone bone = new BabylonBone()
                {
                    name            = currentFullPathName,
                    index           = indexByFullPathName[currentFullPathName],
                    parentBoneIndex = parentIndex,
                    matrix          = ConvertMayaToBabylonMatrix(currentNodeTransform.transformationMatrix).m.ToArray(),
                    animation       = GetAnimationsFrameByFrameMatrix(currentNodeTransform)
                };

                bones.Add(bone);
                RaiseMessage($"Bone: name={bone.name}, index={bone.index}, parentBoneIndex={bone.parentBoneIndex}, matrix={string.Join(" ", bone.matrix)}", logRank + 1);

                // Progress bar
                progressSkin += progressBoneStep;
                ReportProgressChanged(progressSkin);
                CheckCancelled();
            }

            // sort
            List <BabylonBone> sorted = new List <BabylonBone>();

            sorted = bones.OrderBy(bone => bone.index).ToList();
            bones  = sorted;

            RaiseMessage($"{bones.Count} bone(s) exported", logRank + 1);

            return(bones.ToArray());
        }
Esempio n. 10
0
        /// <summary>
        /// Init the dictionary of the skin. This dictionary represents the skeleton. It contains the node names and their index.
        /// And add it to skinDictionary
        /// </summary>
        /// <param name="skin">the skin cluster</param>
        /// <returns>
        /// The dictionary that represents the skin skeleton
        /// </returns>
        private Dictionary <string, int> GetIndexByFullPathNameDictionary(MFnSkinCluster skin)
        {
            if (skinDictionary.ContainsKey(skin.name))
            {
                return(skinDictionary[skin.name]);
            }
            Dictionary <string, int> indexByFullPathName = new Dictionary <string, int>();
            List <MObject>           revelantNodes       = GetRevelantNodes(skin);

            // get the root node
            MObject rootNode = GetRootNode(skin);
            // Travel the DAG
            MItDag dagIterator = new MItDag(MItDag.TraversalType.kDepthFirst);

            dagIterator.reset(rootNode);
            int index = 0;

            while (!dagIterator.isDone)
            {
                // current node
                MDagPath mDagPath = new MDagPath();
                dagIterator.getPath(mDagPath);
                MObject currentNode = mDagPath.node;

                try
                {
                    if (revelantNodes.Count(node => Equals(node, currentNode)) > 0)
                    {
                        MFnTransform currentNodeTransform = new MFnTransform(currentNode);
                        string       currentFullPathName  = currentNodeTransform.fullPathName;

                        indexByFullPathName.Add(currentFullPathName, index);
                        index++;
                    }
                }
                catch   // When it's not a kTransform or kJoint node. For exemple a kLocator, kNurbsCurve.
                {
                    RaiseError($"{currentNode.apiType} is not supported. It will not be exported: {mDagPath.fullPathName}", 3);
                    return(null);
                }

                dagIterator.next();
            }

            skinDictionary.Add(skin.name, indexByFullPathName);

            return(indexByFullPathName);
        }
Esempio n. 11
0
        /// <summary>
        /// Create the BabylonSkeleton from the Maya MFnSkinCluster.
        /// And add it to the BabylonScene.
        /// </summary>
        /// <param name="skin">The maya skin cluster</param>
        /// <param name="babylonScene">The scene to export</param>
        /// <returns></returns>
        private void ExportSkin(MFnSkinCluster skin, BabylonScene babylonScene)
        {
            int    logRank   = 1;
            int    skinIndex = GetSkeletonIndex(skin);
            string name      = "skeleton #" + skinIndex;

            RaiseMessage(name, logRank);

            BabylonSkeleton babylonSkeleton = new BabylonSkeleton {
                id    = skinIndex,
                name  = name,
                bones = ExportBones(skin),
                needInitialSkinMatrix = true
            };

            babylonScene.SkeletonsList.Add(babylonSkeleton);
        }
Esempio n. 12
0
        /// <summary>
        /// The MEL command only return name and not fullPathName. Unfortunatly you need the full path name to differentiate two nodes with the same names.
        ///
        /// </summary>
        /// <param name="skin">The skin cluster</param>
        /// <param name="transform">The transform above the mesh</param>
        /// <returns>
        /// The array with the node full path names.
        /// </returns>
        private MStringArray GetBoneFullPathName(MFnSkinCluster skin, MFnTransform transform)
        {
            int logRank = 3;

            // Get the bone names that influence the mesh
            // We need to keep this order as we will use an other mel command to get the weight influence
            MStringArray mayaInfluenceNames = new MStringArray();

            MGlobal.executeCommand($"skinCluster -q -influence {transform.name}", mayaInfluenceNames);

            List <string> boneFullPathNames = new List <string>();
            MPlugArray    connections       = new MPlugArray();

            // Get the bone full path names of the skin cluster
            foreach (MObject node in GetInfluentNodes(skin))
            {
                boneFullPathNames.Add((new MFnDagNode(node)).fullPathName);
            }

            // Change the name to the fullPathName. And check that they all share the same root node.
            string rootName = "";

            for (int index = 0; index < mayaInfluenceNames.Count; index++)
            {
                string name              = mayaInfluenceNames[index];
                string name_substring    = "|" + name;
                int    indexFullPathName = boneFullPathNames.FindIndex(fullPathName => fullPathName.EndsWith(name_substring));
                mayaInfluenceNames[index] = boneFullPathNames[indexFullPathName];

                if (index == 0)
                {
                    rootName = mayaInfluenceNames[index].Split('|')[1];
                    RaiseVerbose($"rootName: {rootName}", logRank + 1);
                }
                RaiseVerbose($"{index}: {name} => {mayaInfluenceNames[index]}", logRank + 1);

                if (!mayaInfluenceNames[index].StartsWith($"|{rootName}|") && !mayaInfluenceNames[index].Equals($"|{rootName}"))
                {
                    RaiseError($"Bones don't share the same root node. {rootName} != {mayaInfluenceNames[index].Split('|')[1]}", logRank);
                    return(null);
                }
            }

            return(mayaInfluenceNames);
        }
Esempio n. 13
0
        private MFnSkinCluster getMFnSkinCluster(MObject mObject)
        {
            MFnSkinCluster mFnSkinCluster = null;

            MFnDependencyNode mFnDependencyNode = new MFnDependencyNode(mObject);
            MPlugArray        connections       = new MPlugArray();

            mFnDependencyNode.getConnections(connections);
            for (int index = 0; index < connections.Count && mFnSkinCluster == null; index++)
            {
                MObject source = connections[index].source.node;
                if (source != null && source.hasFn(MFn.Type.kSkinClusterFilter))
                {
                    mFnSkinCluster = new MFnSkinCluster(source);
                }
            }

            return(mFnSkinCluster);
        }
Esempio n. 14
0
        /// <summary>
        /// Return the max influence of a skin cluster on a mesh.
        /// </summary>
        /// <param name="skin">the skin</param>
        /// <param name="transform">the transform above the mesh</param>
        /// <param name="mesh">the mesh</param>
        /// <returns>The max influence</returns>
        private int GetMaxInfluence(MFnSkinCluster skin, MFnTransform transform, MFnMesh mesh)
        {
            int maxNumInfluences = 0;
            int numVertices      = mesh.numVertices;

            // Get max influence on a vertex
            for (int index = 0; index < numVertices; index++)
            {
                MDoubleArray influenceWeights = new MDoubleArray();
                String       command          = $"skinPercent -query -value {skin.name} {transform.name}.vtx[{index}]";
                // Get the weight values of all the influences for this vertex
                MGlobal.executeCommand(command, influenceWeights);

                int numInfluences = influenceWeights.Count(weight => weight != 0);

                maxNumInfluences = Math.Max(maxNumInfluences, numInfluences);
            }

            return(maxNumInfluences);
        }
Esempio n. 15
0
        public void Create(SKLFile skl)
        {
            MSelectionList   currentSelection         = MGlobal.activeSelectionList;
            MItSelectionList currentSelectionIterator = new MItSelectionList(currentSelection, MFn.Type.kMesh);
            MDagPath         meshDagPath = new MDagPath();

            if (currentSelectionIterator.isDone)
            {
                MGlobal.displayError("SKNFile:Create - No mesh selected!");
                throw new Exception("SKNFile:Create - No mesh selected!");
            }
            else
            {
                currentSelectionIterator.getDagPath(meshDagPath);
                currentSelectionIterator.next();

                if (!currentSelectionIterator.isDone)
                {
                    MGlobal.displayError("SKNFile:Create - More than one mesh selected!");
                    throw new Exception("SKNFile:Create - More than one mesh selected!");
                }
            }

            MFnMesh mesh = new MFnMesh(meshDagPath);

            //Find Skin Cluster
            MPlug      inMeshPlug        = mesh.findPlug("inMesh");
            MPlugArray inMeshConnections = new MPlugArray();

            inMeshPlug.connectedTo(inMeshConnections, true, false);
            if (inMeshConnections.length == 0)
            {
                MGlobal.displayError("SKNFile:Create - Failed to find Skin Cluster!");
                throw new Exception("SKNFile:Create - Failed to find Skin Cluster!");
            }

            MPlug          outputGeometryPlug = inMeshConnections[0];
            MFnSkinCluster skinCluster        = new MFnSkinCluster(outputGeometryPlug.node);
            MDagPathArray  influenceDagPaths  = new MDagPathArray();
            uint           influenceCount     = skinCluster.influenceObjects(influenceDagPaths);

            MGlobal.displayInfo("SKNFile:Create - Influence Count: " + influenceCount);

            //Get SKL Influence Indices
            MIntArray sklInfluenceIndices = new MIntArray(influenceCount);

            for (int i = 0; i < influenceCount; i++)
            {
                MDagPath jointDagPath = influenceDagPaths[i];

                MGlobal.displayInfo(jointDagPath.fullPathName);

                //Loop through Joint DAG Paths, if we find a math for the influence, write the index
                for (int j = 0; j < skl.JointDagPaths.Count; j++)
                {
                    if (jointDagPath.equalEqual(skl.JointDagPaths[j]))
                    {
                        MGlobal.displayInfo("Found coresponding DAG path");
                        sklInfluenceIndices[i] = j;
                        break;
                    }
                }
            }

            //Add Influence indices to SKL File
            MIntArray maskInfluenceIndex = new MIntArray(influenceCount);

            for (int i = 0; i < influenceCount; i++)
            {
                maskInfluenceIndex[i] = i;
                skl.Influences.Add((short)sklInfluenceIndices[i]);
            }

            MObjectArray shaders = new MObjectArray();
            MIntArray    polygonShaderIndices = new MIntArray();

            mesh.getConnectedShaders(meshDagPath.isInstanced ? meshDagPath.instanceNumber : 0, shaders, polygonShaderIndices);

            uint shaderCount = shaders.length;

            if (shaderCount > 32) //iirc 32 is the limit of how many submeshes there can be for an SKN file
            {
                MGlobal.displayError("SKNFile:Create - You've exceeded the maximum limit of 32 shaders");
                throw new Exception("SKNFile:Create - You've exceeded the maximum limit of 32 shaders");
            }

            MIntArray vertexShaders = new MIntArray();

            ValidateMeshTopology(mesh, meshDagPath, polygonShaderIndices, ref vertexShaders, shaderCount);

            //Get Weights
            MFnSingleIndexedComponent vertexIndexedComponent = new MFnSingleIndexedComponent();
            MObject   vertexComponent    = vertexIndexedComponent.create(MFn.Type.kMeshVertComponent);
            MIntArray groupVertexIndices = new MIntArray((uint)mesh.numVertices);

            for (int i = 0; i < mesh.numVertices; i++)
            {
                groupVertexIndices[i] = i;
            }
            vertexIndexedComponent.addElements(groupVertexIndices);

            MDoubleArray weights = new MDoubleArray();
            uint         weightsInfluenceCount = 0;

            skinCluster.getWeights(meshDagPath, vertexComponent, weights, ref weightsInfluenceCount);

            //Check if vertices don't have more than 4 influences and normalize weights
            for (int i = 0; i < mesh.numVertices; i++)
            {
                int    vertexInfluenceCount = 0;
                double weightSum            = 0;
                for (int j = 0; j < weightsInfluenceCount; j++)
                {
                    double weight = weights[(int)(i * weightsInfluenceCount) + j];
                    if (weight != 0)
                    {
                        vertexInfluenceCount++;
                        weightSum += weight;
                    }
                }

                if (vertexInfluenceCount > 4)
                {
                    MGlobal.displayError("SKNFile:Create - Mesh contains a vertex with more than 4 influences");
                    throw new Exception("SKNFile:Create - Mesh contains a vertex with more than 4 influences");
                }

                //Normalize weights
                for (int j = 0; j < weightsInfluenceCount; j++)
                {
                    weights[(int)(i * influenceCount) + j] /= weightSum;
                }
            }

            List <MIntArray>         shaderVertexIndices = new List <MIntArray>();
            List <List <SKNVertex> > shaderVertices      = new List <List <SKNVertex> >();
            List <MIntArray>         shaderIndices       = new List <MIntArray>();

            for (int i = 0; i < shaderCount; i++)
            {
                shaderVertexIndices.Add(new MIntArray());
                shaderVertices.Add(new List <SKNVertex>());
                shaderIndices.Add(new MIntArray());
            }

            MItMeshVertex meshVertexIterator = new MItMeshVertex(meshDagPath);

            for (meshVertexIterator.reset(); !meshVertexIterator.isDone; meshVertexIterator.next())
            {
                int index  = meshVertexIterator.index();
                int shader = vertexShaders[index];
                if (shader == -1)
                {
                    MGlobal.displayWarning("SKNFile:Create - Mesh contains a vertex with no shader");
                    continue;
                }

                MPoint       pointPosition = meshVertexIterator.position(MSpace.Space.kWorld);
                Vector3      position      = new Vector3((float)pointPosition.x, (float)pointPosition.y, (float)pointPosition.z);
                MVectorArray normals       = new MVectorArray();
                MIntArray    uvIndices     = new MIntArray();
                Vector3      normal        = new Vector3();
                byte[]       weightIndices = new byte[4];
                float[]      vertexWeights = new float[4];

                meshVertexIterator.getNormals(normals);

                //Normalize normals
                for (int i = 0; i < normals.length; i++)
                {
                    normal.X += (float)normals[i].x;
                    normal.Y += (float)normals[i].y;
                    normal.Z += (float)normals[i].z;
                }

                normal.X /= normals.length;
                normal.Y /= normals.length;
                normal.Z /= normals.length;

                //Get Weight Influences and Weights
                int weightsFound = 0;
                for (int j = 0; j < weightsInfluenceCount && weightsFound < 4; j++)
                {
                    double weight = weights[(int)(index * weightsInfluenceCount) + j];

                    if (weight != 0)
                    {
                        weightIndices[weightsFound] = (byte)maskInfluenceIndex[j];
                        vertexWeights[weightsFound] = (float)weight;
                        weightsFound++;
                    }
                }

                //Get unique UVs
                meshVertexIterator.getUVIndices(uvIndices);
                if (uvIndices.length != 0)
                {
                    List <int> seen = new List <int>();
                    for (int j = 0; j < uvIndices.length; j++)
                    {
                        int uvIndex = uvIndices[j];
                        if (!seen.Contains(uvIndex))
                        {
                            seen.Add(uvIndex);

                            float u = 0;
                            float v = 0;
                            mesh.getUV(uvIndex, ref u, ref v);

                            SKNVertex vertex = new SKNVertex(position, weightIndices, vertexWeights, normal, new Vector2(u, 1 - v));
                            vertex.UVIndex = uvIndex;

                            shaderVertices[shader].Add(vertex);
                            shaderVertexIndices[shader].append(index);
                        }
                    }
                }
                else
                {
                    MGlobal.displayError("SKNFile:Create - Mesh contains a vertex with no UVs");
                    throw new Exception("SKNFile:Create - Mesh contains a vertex with no UVs");
                }
            }

            //Convert from Maya indices to data indices
            int       currentIndex = 0;
            MIntArray dataIndices  = new MIntArray((uint)mesh.numVertices, -1);

            for (int i = 0; i < shaderCount; i++)
            {
                for (int j = 0; j < shaderVertexIndices[i].length; j++)
                {
                    int index = shaderVertexIndices[i][j];
                    if (dataIndices[index] == -1)
                    {
                        dataIndices[index]             = currentIndex;
                        shaderVertices[i][j].DataIndex = currentIndex;
                    }
                    else
                    {
                        shaderVertices[i][j].DataIndex = dataIndices[index];
                    }

                    currentIndex++;
                }

                this.Vertices.AddRange(shaderVertices[i]);
            }

            MItMeshPolygon polygonIterator = new MItMeshPolygon(meshDagPath);

            for (polygonIterator.reset(); !polygonIterator.isDone; polygonIterator.next())
            {
                int polygonIndex = (int)polygonIterator.index();
                int shaderIndex  = polygonShaderIndices[polygonIndex];

                MIntArray   indices = new MIntArray();
                MPointArray points  = new MPointArray();
                polygonIterator.getTriangles(points, indices);

                if (polygonIterator.hasUVsProperty)
                {
                    MIntArray vertices   = new MIntArray();
                    MIntArray newIndices = new MIntArray(indices.length, -1);
                    polygonIterator.getVertices(vertices);

                    for (int i = 0; i < vertices.length; i++)
                    {
                        int dataIndex = dataIndices[vertices[i]];
                        int uvIndex;
                        polygonIterator.getUVIndex(i, out uvIndex);

                        if (dataIndex == -1 || dataIndex >= this.Vertices.Count)
                        {
                            MGlobal.displayError("SKNFIle:Create - Data Index outside of range");
                            throw new Exception("SKNFIle:Create - Data Index outside of range");
                        }

                        for (int j = dataIndex; j < this.Vertices.Count; j++)
                        {
                            if (this.Vertices[j].DataIndex != dataIndex)
                            {
                                MGlobal.displayError("SKNFIle:Create - Can't find corresponding face vertex in data");
                                throw new Exception("SKNFIle:Create - Can't find corresponding face vertex in data");
                            }
                            else if (this.Vertices[j].UVIndex == uvIndex)
                            {
                                for (int k = 0; k < indices.length; k++)
                                {
                                    if (indices[k] == vertices[i])
                                    {
                                        newIndices[k] = j;
                                    }
                                }

                                break;
                            }
                        }
                    }

                    for (int i = 0; i < newIndices.length; i++)
                    {
                        shaderIndices[shaderIndex].append(newIndices[i]);
                    }
                }
                else
                {
                    for (int i = 0; i < indices.length; i++)
                    {
                        shaderIndices[shaderIndex].append(dataIndices[indices[i]]);
                    }
                }
            }

            uint startIndex  = 0;
            uint startVertex = 0;

            for (int i = 0; i < shaderCount; i++)
            {
                MPlug      shaderPlug = new MFnDependencyNode(shaders[i]).findPlug("surfaceShader");
                MPlugArray plugArray  = new MPlugArray();
                shaderPlug.connectedTo(plugArray, true, false);

                string name        = new MFnDependencyNode(plugArray[0].node).name;
                uint   indexCount  = shaderIndices[i].length;
                uint   vertexCount = shaderVertexIndices[i].length;

                //Copy indices to SKLFile
                for (int j = 0; j < indexCount; j++)
                {
                    this.Indices.Add((ushort)shaderIndices[i][j]);
                }

                this.Submeshes.Add(new SKNSubmesh(name, startVertex, vertexCount, startIndex, indexCount));

                startIndex  += indexCount;
                startVertex += vertexCount;
            }

            MGlobal.displayInfo("SKNFile:Create - Created SKN File");
        }
Esempio n. 16
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();
            }
        }
Esempio n. 17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="mDagPath">DAG path to the transform above mesh</param>
        /// <param name="babylonScene"></param>
        /// <returns></returns>
        private BabylonNode ExportMesh(MDagPath mDagPath, BabylonScene babylonScene)
        {
            RaiseMessage(mDagPath.partialPathName, 1);

            // Transform above mesh
            mFnTransform = new MFnTransform(mDagPath);

            // Mesh direct child of the transform
            // TODO get the original one rather than the modified?
            MFnMesh mFnMesh = null;

            for (uint i = 0; i < mFnTransform.childCount; i++)
            {
                MObject childObject = mFnTransform.child(i);
                if (childObject.apiType == MFn.Type.kMesh)
                {
                    var _mFnMesh = new MFnMesh(childObject);
                    if (!_mFnMesh.isIntermediateObject)
                    {
                        mFnMesh = _mFnMesh;
                    }
                }
            }
            if (mFnMesh == null)
            {
                RaiseError("No mesh found has child of " + mDagPath.fullPathName);
                return(null);
            }

            RaiseMessage("mFnMesh.fullPathName=" + mFnMesh.fullPathName, 2);

            // --- prints ---
            #region prints

            Action <MFnDagNode> printMFnDagNode = (MFnDagNode mFnDagNode) =>
            {
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.name=" + mFnDagNode.name, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.absoluteName=" + mFnDagNode.absoluteName, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.fullPathName=" + mFnDagNode.fullPathName, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.partialPathName=" + mFnDagNode.partialPathName, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.activeColor=" + mFnDagNode.activeColor.toString(), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.attributeCount=" + mFnDagNode.attributeCount, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.childCount=" + mFnDagNode.childCount, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.dormantColor=" + mFnDagNode.dormantColor, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.hasUniqueName=" + mFnDagNode.hasUniqueName, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.inUnderWorld=" + mFnDagNode.inUnderWorld, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.isDefaultNode=" + mFnDagNode.isDefaultNode, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.isInstanceable=" + mFnDagNode.isInstanceable, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.isInstanced(true)=" + mFnDagNode.isInstanced(true), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.isInstanced(false)=" + mFnDagNode.isInstanced(false), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.isInstanced()=" + mFnDagNode.isInstanced(), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.instanceCount(true)=" + mFnDagNode.instanceCount(true), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.instanceCount(false)=" + mFnDagNode.instanceCount(false), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.isIntermediateObject=" + mFnDagNode.isIntermediateObject, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.isShared=" + mFnDagNode.isShared, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.objectColor=" + mFnDagNode.objectColor, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.parentCount=" + mFnDagNode.parentCount, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.parentNamespace=" + mFnDagNode.parentNamespace, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.uuid().asString()=" + mFnDagNode.uuid().asString(), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.dagRoot().apiType=" + mFnDagNode.dagRoot().apiType, 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.model.equalEqual(mFnDagNode.objectProperty)=" + mFnDagNode.model.equalEqual(mFnDagNode.objectProperty), 3);
                RaiseVerbose("BabylonExporter.Mesh | mFnDagNode.transformationMatrix.toString()=" + mFnDagNode.transformationMatrix.toString(), 3);
            };

            Action <MFnMesh> printMFnMesh = (MFnMesh _mFnMesh) =>
            {
                printMFnDagNode(mFnMesh);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numVertices=" + _mFnMesh.numVertices, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numEdges=" + _mFnMesh.numEdges, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numPolygons=" + _mFnMesh.numPolygons, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numFaceVertices=" + _mFnMesh.numFaceVertices, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numNormals=" + _mFnMesh.numNormals, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numUVSets=" + _mFnMesh.numUVSets, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numUVsProperty=" + _mFnMesh.numUVsProperty, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.displayColors=" + _mFnMesh.displayColors, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numColorSets=" + _mFnMesh.numColorSets, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.numColorsProperty=" + _mFnMesh.numColorsProperty, 3);
                RaiseVerbose("BabylonExporter.Mesh | _mFnMesh.currentUVSetName()=" + _mFnMesh.currentUVSetName(), 3);

                var _uvSetNames = new MStringArray();
                mFnMesh.getUVSetNames(_uvSetNames);
                foreach (var uvSetName in _uvSetNames)
                {
                    RaiseVerbose("BabylonExporter.Mesh | uvSetName=" + uvSetName, 3);
                    RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numUVs(uvSetName)=" + mFnMesh.numUVs(uvSetName), 4);
                    MFloatArray us = new MFloatArray();
                    MFloatArray vs = new MFloatArray();
                    mFnMesh.getUVs(us, vs, uvSetName);
                    RaiseVerbose("BabylonExporter.Mesh | us.Count=" + us.Count, 4);
                }
            };

            Action <MFnTransform> printMFnTransform = (MFnTransform _mFnMesh) =>
            {
                printMFnDagNode(mFnMesh);
            };

            RaiseVerbose("BabylonExporter.Mesh | mFnMesh data", 2);
            printMFnMesh(mFnMesh);

            RaiseVerbose("BabylonExporter.Mesh | mFnTransform data", 2);
            printMFnTransform(mFnTransform);

            Print(mFnTransform, 2, "Print ExportMesh mFnTransform");

            Print(mFnMesh, 2, "Print ExportMesh mFnMesh");

            //// Geometry
            //MIntArray triangleCounts = new MIntArray();
            //MIntArray trianglesVertices = new MIntArray();
            //mFnMesh.getTriangles(triangleCounts, trianglesVertices);
            //RaiseVerbose("BabylonExporter.Mesh | triangleCounts.ToArray()=" + triangleCounts.ToArray().toString(), 3);
            //RaiseVerbose("BabylonExporter.Mesh | trianglesVertices.ToArray()=" + trianglesVertices.ToArray().toString(), 3);
            //int[] polygonsVertexCount = new int[mFnMesh.numPolygons];
            //for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++)
            //{
            //    polygonsVertexCount[polygonId] = mFnMesh.polygonVertexCount(polygonId);
            //}
            //RaiseVerbose("BabylonExporter.Mesh | polygonsVertexCount=" + polygonsVertexCount.toString(), 3);

            ////MFloatPointArray points = new MFloatPointArray();
            ////mFnMesh.getPoints(points);
            ////RaiseVerbose("BabylonExporter.Mesh | points.ToArray()=" + points.ToArray().Select(mFloatPoint => mFloatPoint.toString()), 3);

            ////MFloatVectorArray normals = new MFloatVectorArray();
            ////mFnMesh.getNormals(normals);
            ////RaiseVerbose("BabylonExporter.Mesh | normals.ToArray()=" + normals.ToArray().Select(mFloatPoint => mFloatPoint.toString()), 3);

            //for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++)
            //{
            //    MIntArray verticesId = new MIntArray();
            //    RaiseVerbose("BabylonExporter.Mesh | polygonId=" + polygonId, 3);

            //    int nbTriangles = triangleCounts[polygonId];
            //    RaiseVerbose("BabylonExporter.Mesh | nbTriangles=" + nbTriangles, 3);

            //    for (int triangleIndex = 0; triangleIndex < triangleCounts[polygonId]; triangleIndex++)
            //    {
            //        RaiseVerbose("BabylonExporter.Mesh | triangleIndex=" + triangleIndex, 3);
            //        int[] triangleVertices = new int[3];
            //        mFnMesh.getPolygonTriangleVertices(polygonId, triangleIndex, triangleVertices);
            //        RaiseVerbose("BabylonExporter.Mesh | triangleVertices=" + triangleVertices.toString(), 3);

            //        foreach (int vertexId in triangleVertices)
            //        {
            //            RaiseVerbose("BabylonExporter.Mesh | vertexId=" + vertexId, 3);
            //            MPoint point = new MPoint();
            //            mFnMesh.getPoint(vertexId, point);
            //            RaiseVerbose("BabylonExporter.Mesh | point=" + point.toString(), 3);

            //            MVector normal = new MVector();
            //            mFnMesh.getFaceVertexNormal(polygonId, vertexId, normal);
            //            RaiseVerbose("BabylonExporter.Mesh | normal=" + normal.toString(), 3);
            //        }
            //    }
            //}

            #endregion

            if (IsMeshExportable(mFnMesh, mDagPath) == false)
            {
                return(null);
            }

            var babylonMesh = new BabylonMesh {
                name = mFnTransform.name, id = mFnTransform.uuid().asString()
            };

            // Position / rotation / scaling / hierarchy
            ExportNode(babylonMesh, mFnTransform, babylonScene);

            // Misc.
            // TODO - Retreive from Maya
            // TODO - What is the difference between isVisible and visibility?
            // TODO - Fix fatal error: Attempting to save in C:/Users/Fabrice/AppData/Local/Temp/Fabrice.20171205.1613.ma
            //babylonMesh.isVisible = mDagPath.isVisible;
            //babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
            //babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
            //babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1;

            if (mFnMesh.numPolygons < 1)
            {
                RaiseError($"Mesh {babylonMesh.name} has no face", 2);
            }

            if (mFnMesh.numVertices < 3)
            {
                RaiseError($"Mesh {babylonMesh.name} has not enough vertices", 2);
            }

            if (mFnMesh.numVertices >= 65536)
            {
                RaiseWarning($"Mesh {babylonMesh.name} has more than 65536 vertices which means that it will require specific WebGL extension to be rendered. This may impact portability of your scene on low end devices.", 2);
            }

            // Animations
            ExportNodeAnimation(babylonMesh, mFnTransform);

            // Material
            MObjectArray shaders = new MObjectArray();
            mFnMesh.getConnectedShaders(0, shaders, new MIntArray());
            if (shaders.Count > 0)
            {
                List <MFnDependencyNode> materials = new List <MFnDependencyNode>();
                foreach (MObject shader in shaders)
                {
                    // Retreive material
                    MFnDependencyNode shadingEngine      = new MFnDependencyNode(shader);
                    MPlug             mPlugSurfaceShader = shadingEngine.findPlug("surfaceShader");
                    MObject           materialObject     = mPlugSurfaceShader.source.node;
                    MFnDependencyNode material           = new MFnDependencyNode(materialObject);

                    materials.Add(material);
                }

                if (shaders.Count == 1)
                {
                    MFnDependencyNode material = materials[0];

                    // Material is referenced by id
                    babylonMesh.materialId = material.uuid().asString();

                    // Register material for export if not already done
                    if (!referencedMaterials.Contains(material, new MFnDependencyNodeEqualityComparer()))
                    {
                        referencedMaterials.Add(material);
                    }
                }
                else
                {
                    // Create a new id for the group of sub materials
                    string uuidMultiMaterial = GetMultimaterialUUID(materials);

                    // Multi material is referenced by id
                    babylonMesh.materialId = uuidMultiMaterial;

                    // Register multi material for export if not already done
                    if (!multiMaterials.ContainsKey(uuidMultiMaterial))
                    {
                        multiMaterials.Add(uuidMultiMaterial, materials);
                    }
                }
            }

            var vertices = new List <GlobalVertex>();
            var indices  = new List <int>();

            var uvSetNames = new MStringArray();
            mFnMesh.getUVSetNames(uvSetNames);
            bool[] isUVExportSuccess = new bool[Math.Min(uvSetNames.Count, 2)];
            for (int indexUVSet = 0; indexUVSet < isUVExportSuccess.Length; indexUVSet++)
            {
                isUVExportSuccess[indexUVSet] = true;
            }

            // skin
            if (_exportSkin)
            {
                mFnSkinCluster = getMFnSkinCluster(mFnMesh);
            }
            int maxNbBones = 0;
            if (mFnSkinCluster != null)
            {
                RaiseMessage($"mFnSkinCluster.name | {mFnSkinCluster.name}", 2);
                Print(mFnSkinCluster, 3, $"Print {mFnSkinCluster.name}");

                // Get the bones dictionary<name, index> => it represents all the bones in the skeleton
                indexByNodeName = GetIndexByFullPathNameDictionary(mFnSkinCluster);

                // Get the joint names that influence this mesh
                allMayaInfluenceNames = GetBoneFullPathName(mFnSkinCluster, mFnTransform);

                // Get the max number of joints acting on a vertex
                int maxNumInfluences = GetMaxInfluence(mFnSkinCluster, mFnTransform, mFnMesh);

                RaiseMessage($"Max influences : {maxNumInfluences}", 2);
                if (maxNumInfluences > 8)
                {
                    RaiseWarning($"Too many bones influences per vertex: {maxNumInfluences}. Babylon.js only support up to 8 bones influences per vertex.", 2);
                    RaiseWarning("The result may not be as expected.", 2);
                }
                maxNbBones = Math.Min(maxNumInfluences, 8);

                if (indexByNodeName != null && allMayaInfluenceNames != null)
                {
                    babylonMesh.skeletonId = GetSkeletonIndex(mFnSkinCluster);
                }
                else
                {
                    mFnSkinCluster = null;
                }
            }
            // Export tangents if option is checked and mesh have tangents
            bool isTangentExportSuccess = _exportTangents;

            // TODO - color, alpha
            //var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
            //var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;

            // TODO - Add custom properties
            //var optimizeVertices = false; // meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");
            var optimizeVertices = _optimizeVertices; // global option

            // Compute normals
            var subMeshes = new List <BabylonSubMesh>();
            ExtractGeometry(mFnMesh, vertices, indices, subMeshes, uvSetNames, ref isUVExportSuccess, ref isTangentExportSuccess, optimizeVertices);

            if (vertices.Count >= 65536)
            {
                RaiseWarning($"Mesh {babylonMesh.name} has {vertices.Count} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", 2);

                if (!optimizeVertices)
                {
                    RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
                }
            }

            for (int indexUVSet = 0; indexUVSet < isUVExportSuccess.Length; indexUVSet++)
            {
                string uvSetName = uvSetNames[indexUVSet];
                // If at least one vertex is mapped to an UV coordinate but some have failed to be exported
                if (isUVExportSuccess[indexUVSet] == false && mFnMesh.numUVs(uvSetName) > 0)
                {
                    RaiseWarning($"Failed to export UV set named {uvSetName}. Ensure all vertices are mapped to a UV coordinate.", 2);
                }
            }

            RaiseMessage($"{vertices.Count} vertices, {indices.Count / 3} faces", 2);

            // Buffers
            babylonMesh.positions = vertices.SelectMany(v => v.Position).ToArray();
            babylonMesh.normals   = vertices.SelectMany(v => v.Normal).ToArray();

            // export the skin
            if (mFnSkinCluster != null)
            {
                babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
                babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();

                babylonMesh.numBoneInfluencers = maxNbBones;
                if (maxNbBones > 4)
                {
                    babylonMesh.matricesWeightsExtra = vertices.SelectMany(v => v.WeightsExtra != null ? v.WeightsExtra.ToArray() : new[] { 0.0f, 0.0f, 0.0f, 0.0f }).ToArray();
                    babylonMesh.matricesIndicesExtra = vertices.Select(v => v.BonesIndicesExtra).ToArray();
                }
            }

            // Tangent
            if (isTangentExportSuccess)
            {
                babylonMesh.tangents = vertices.SelectMany(v => v.Tangent).ToArray();
            }
            // Color
            string colorSetName;
            mFnMesh.getCurrentColorSetName(out colorSetName);
            if (mFnMesh.numColors(colorSetName) > 0)
            {
                babylonMesh.colors = vertices.SelectMany(v => v.Color).ToArray();
            }
            // UVs
            if (uvSetNames.Count > 0 && isUVExportSuccess[0])
            {
                babylonMesh.uvs = vertices.SelectMany(v => v.UV).ToArray();
            }
            if (uvSetNames.Count > 1 && isUVExportSuccess[1])
            {
                babylonMesh.uvs2 = vertices.SelectMany(v => v.UV2).ToArray();
            }

            babylonMesh.subMeshes = subMeshes.ToArray();

            // Buffers - Indices
            babylonMesh.indices = indices.ToArray();


            babylonScene.MeshesList.Add(babylonMesh);
            RaiseMessage("BabylonExporter.Mesh | done", 2);

            return(babylonMesh);
        }
        public override void doIt(MArgList args)
        {
            // parse args to get the file name from the command-line
            //
            parseArgs(args);
            uint count = 0;

            // Iterate through graph and search for skinCluster nodes
            //
            MItDependencyNodes iter = new MItDependencyNodes( MFn.Type.kInvalid);
            for ( ; !iter.isDone; iter.next() )
            {
                MObject obj = iter.item;
                if (obj.apiType == MFn.Type.kSkinClusterFilter)
                {
                    count++;

                    // For each skinCluster node, get the list of influence objects
                    //
                    MFnSkinCluster skinCluster = new MFnSkinCluster(obj);
                    MDagPathArray infs = new MDagPathArray();
                    uint nInfs;
                    try
                    {
                        nInfs = skinCluster.influenceObjects(infs);
                    }
                    catch (Exception)
                    {
                        MGlobal.displayInfo("Error getting influence objects.");
                        continue;
                    }
                    if (0 == nInfs)
                    {
                        MGlobal.displayInfo("Error: No influence objects found.");
                        continue;
                    }

                    // loop through the geometries affected by this cluster
                    //
                    uint nGeoms = skinCluster.numOutputConnections;
                    for (uint ii = 0; ii < nGeoms; ++ii)
                    {
                        uint index;
                        try
                        {
                            index = skinCluster.indexForOutputConnection(ii);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry index.");
                            continue;
                        }

                        // get the dag path of the ii'th geometry
                        //
                        MDagPath skinPath = new MDagPath();
                        try{
                        skinCluster.getPathAtIndex(index,skinPath);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry path.");
                            continue;
                        }

                        // iterate through the components of this geometry
                        //
                        MItGeometry gIter = new MItGeometry(skinPath);

                        // print out the path name of the skin, vertexCount & influenceCount
                        //
                        UnicodeEncoding uniEncoding = new UnicodeEncoding();
                        string res = String.Format("{0} {1} {2}\n",skinPath.partialPathName,gIter.count,nInfs);
                        file.Write(uniEncoding.GetBytes(res),0,uniEncoding.GetByteCount(res));

                        // print out the influence objects
                        //
                        for (int kk = 0; kk < nInfs; ++kk)
                        {
                            res = String.Format("{0} ", infs[kk].partialPathName);
                            file.Write(uniEncoding.GetBytes(res),0,uniEncoding.GetByteCount(res));
                        }
                        res = "\n";
                        file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));

                        for ( /* nothing */ ; !gIter.isDone; gIter.next() ) {
                            MObject comp;
                            try
                            {
                                comp = gIter.component;
                            }
                            catch (Exception)
                            {
                                MGlobal.displayInfo("Error getting geometry path.");
                                continue;
                            }

                            // Get the weights for this vertex (one per influence object)
                            //
                            MDoubleArray wts = new MDoubleArray();
                            uint infCount = 0;
                            try
                            {
                                skinCluster.getWeights(skinPath, comp, wts, ref infCount);
                            }
                            catch (Exception)
                            {
                                displayError("Error getting weights.");
                                continue;
                            }
                            if (0 == infCount)
                            {
                                displayError("Error: 0 influence objects.");
                            }

                            // Output the weight data for this vertex
                            //
                            res = String.Format("{0} ",gIter.index);
                            file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            for (int jj = 0; jj < infCount ; ++jj )
                            {
                                res = String.Format("{0} ", wts[jj]);
                                file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            }
                            file.Write(uniEncoding.GetBytes("\n"), 0, uniEncoding.GetByteCount("\n"));
                        }
                    }
                }
            }

            if (0 == count)
            {
                displayError("No skinClusters found in this scene.");
            }
            file.Close();
            return;
        }
        public override void doIt(MArgList args)
        {
            // parse args to get the file name from the command-line
            //
            parseArgs(args);
            uint count = 0;


            // Iterate through graph and search for skinCluster nodes
            //
            MItDependencyNodes iter = new MItDependencyNodes(MFn.Type.kInvalid);

            for ( ; !iter.isDone; iter.next())
            {
                MObject obj = iter.item;
                if (obj.apiType == MFn.Type.kSkinClusterFilter)
                {
                    count++;

                    // For each skinCluster node, get the list of influence objects
                    //
                    MFnSkinCluster skinCluster = new MFnSkinCluster(obj);
                    MDagPathArray  infs        = new MDagPathArray();
                    uint           nInfs;
                    try
                    {
                        nInfs = skinCluster.influenceObjects(infs);
                    }
                    catch (Exception)
                    {
                        MGlobal.displayInfo("Error getting influence objects.");
                        continue;
                    }
                    if (0 == nInfs)
                    {
                        MGlobal.displayInfo("Error: No influence objects found.");
                        continue;
                    }

                    // loop through the geometries affected by this cluster
                    //
                    uint nGeoms = skinCluster.numOutputConnections;
                    for (uint ii = 0; ii < nGeoms; ++ii)
                    {
                        uint index;
                        try
                        {
                            index = skinCluster.indexForOutputConnection(ii);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry index.");
                            continue;
                        }

                        // get the dag path of the ii'th geometry
                        //
                        MDagPath skinPath = new MDagPath();
                        try{
                            skinCluster.getPathAtIndex(index, skinPath);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry path.");
                            continue;
                        }

                        // iterate through the components of this geometry
                        //
                        MItGeometry gIter = new MItGeometry(skinPath);

                        // print out the path name of the skin, vertexCount & influenceCount
                        //
                        UnicodeEncoding uniEncoding = new UnicodeEncoding();
                        string          res         = String.Format("{0} {1} {2}\n", skinPath.partialPathName, gIter.count, nInfs);
                        file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));

                        // print out the influence objects
                        //
                        for (int kk = 0; kk < nInfs; ++kk)
                        {
                            res = String.Format("{0} ", infs[kk].partialPathName);
                            file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                        }
                        res = "\n";
                        file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));

                        for (/* nothing */; !gIter.isDone; gIter.next())
                        {
                            MObject comp;
                            try
                            {
                                comp = gIter.component;
                            }
                            catch (Exception)
                            {
                                MGlobal.displayInfo("Error getting geometry path.");
                                continue;
                            }


                            // Get the weights for this vertex (one per influence object)
                            //
                            MDoubleArray wts      = new MDoubleArray();
                            uint         infCount = 0;
                            try
                            {
                                skinCluster.getWeights(skinPath, comp, wts, ref infCount);
                            }
                            catch (Exception)
                            {
                                displayError("Error getting weights.");
                                continue;
                            }
                            if (0 == infCount)
                            {
                                displayError("Error: 0 influence objects.");
                            }

                            // Output the weight data for this vertex
                            //
                            res = String.Format("{0} ", gIter.index);
                            file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            for (int jj = 0; jj < infCount; ++jj)
                            {
                                res = String.Format("{0} ", wts[jj]);
                                file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            }
                            file.Write(uniEncoding.GetBytes("\n"), 0, uniEncoding.GetByteCount("\n"));
                        }
                    }
                }
            }

            if (0 == count)
            {
                displayError("No skinClusters found in this scene.");
            }
            file.Close();
            return;
        }