Пример #1
0
        protected MObject createMesh(MTime time, ref MObject outData)
        {
            int              numVertices, frame;
            float            cubeSize;
            MFloatPointArray points = new MFloatPointArray();
            MFnMesh          meshFS = new MFnMesh();

            // Scale the cube on the frame number, wrap every 10 frames.
            frame = (int)time.asUnits(MTime.Unit.kFilm);
            if (frame == 0)
            {
                frame = 1;
            }
            cubeSize = 0.5f * (float)(frame % 10);

            const int numFaces = 6;

            numVertices = 8;

            MFloatPoint vtx_1 = new MFloatPoint(-cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_2 = new MFloatPoint(cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_3 = new MFloatPoint(cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_4 = new MFloatPoint(-cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_5 = new MFloatPoint(-cubeSize, cubeSize, -cubeSize);
            MFloatPoint vtx_6 = new MFloatPoint(-cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_7 = new MFloatPoint(cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_8 = new MFloatPoint(cubeSize, cubeSize, -cubeSize);

            points.append(vtx_1);
            points.append(vtx_2);
            points.append(vtx_3);
            points.append(vtx_4);
            points.append(vtx_5);
            points.append(vtx_6);
            points.append(vtx_7);
            points.append(vtx_8);


            // Set up an array containing the number of vertices
            // for each of the 6 cube faces (4 verticies per face)
            //
            int[]     face_counts = { 4, 4, 4, 4, 4, 4 };
            MIntArray faceCounts  = new MIntArray(face_counts);

            // Set up and array to assign vertices from points to each face
            //
            int[]     face_connects = { 0, 1, 2, 3,
                                        4,     5, 6, 7,
                                        3,     2, 6, 5,
                                        0,     3, 5, 4,
                                        0,     4, 7, 1,
                                        1,     7, 6, 2 };
            MIntArray faceConnects = new MIntArray(face_connects);

            MObject newMesh = meshFS.create(numVertices, numFaces, points, faceCounts, faceConnects, outData);

            return(newMesh);
        }
Пример #2
0
 public polyPrimitive()
 {
     iarr         = new MFloatPointArray();
     pa           = new MFloatPointArray();
     faceCounts   = new MIntArray();
     faceConnects = new MIntArray();
     dagMod       = new MDagModifier();
     MGlobal.displayInfo("test polyPrimitive.");
 }
        public static List <Vector3> ToVector3List(this MFloatPointArray array)
        {
            List <Vector3> list = new List <Vector3>(array.Count);

            for (int i = 0; i < array.Count; i++)
            {
                list.Add(array[i].ToVector3());
            }

            return(list);
        }
Пример #4
0
        protected MObject createMesh(MTime time, ref MObject outData)
        {
            int numVertices, frame;
            float cubeSize;
            MFloatPointArray points = new MFloatPointArray();
            MFnMesh meshFS = new MFnMesh();

            // Scale the cube on the frame number, wrap every 10 frames.
            frame = (int)time.asUnits(MTime.Unit.kFilm);
            if (frame == 0)
                frame = 1;
            cubeSize = 0.5f * (float)(frame % 10);

            const int numFaces = 6;
            numVertices = 8;

            MFloatPoint vtx_1 = new MFloatPoint(-cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_2 = new MFloatPoint(cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_3 = new MFloatPoint(cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_4 = new MFloatPoint(-cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_5 = new MFloatPoint(-cubeSize, cubeSize, -cubeSize);
            MFloatPoint vtx_6 = new MFloatPoint(-cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_7 = new MFloatPoint(cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_8 = new MFloatPoint(cubeSize, cubeSize, -cubeSize);
            points.append(vtx_1);
            points.append(vtx_2);
            points.append(vtx_3);
            points.append(vtx_4);
            points.append(vtx_5);
            points.append(vtx_6);
            points.append(vtx_7);
            points.append(vtx_8);


            // Set up an array containing the number of vertices
            // for each of the 6 cube faces (4 verticies per face)
            //
            int[] face_counts = { 4, 4, 4, 4, 4, 4 };
            MIntArray faceCounts = new MIntArray(face_counts);

            // Set up and array to assign vertices from points to each face 
            //
            int[] face_connects = {	0, 1, 2, 3,
									4, 5, 6, 7,
									3, 2, 6, 5,
									0, 3, 5, 4,
									0, 4, 7, 1,
									1, 7, 6, 2	};
            MIntArray faceConnects = new MIntArray(face_connects);

            MObject newMesh = meshFS.create(numVertices, numFaces, points, faceCounts, faceConnects, outData);

            return newMesh;
        }
Пример #5
0
        /// <summary>
        /// Extract the vertices, normals and triangles of a mesh into the M2 collision data fields.
        /// </summary>
        /// <param name="wowModel"></param>
        private static void InjectCollisionMesh(M2 wowModel)
        {
            var collisionFound = false;

            for (var meshIter = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kMesh);
                 !meshIter.isDone; meshIter.next())
            {
                var meshPath = new MDagPath();
                meshIter.getPath(meshPath);

                var meshFn = new MFnMesh(meshPath);
                // only want non-history items
                if (meshFn.isIntermediateObject)
                {
                    continue;
                }
                var name = meshFn.name;
                if (name != "Collision")
                {
                    continue;                     //TODO use custom attribute
                }
                if (collisionFound)
                {
                    throw new Exception("More than one collision box has been found. One supported.");
                }
                MGlobal.displayInfo("\t Collision mesh detected.");

                wowModel.CollisionBox = new CAaBox(AxisInvert(meshFn.boundingBox.min),
                                                   AxisInvert(meshFn.boundingBox.max));
                wowModel.CollisionSphereRadius =
                    (float)Math.Max(meshFn.boundingBox.depth / 2, meshFn.boundingBox.width / 2);

                //TODO fixme better iterate through faces
                var collisionPoints = new MFloatPointArray();
                meshFn.getPoints(collisionPoints, MSpace.Space.kWorld);
                var collisionNormals = new MFloatVectorArray();
                meshFn.getNormals(collisionNormals, MSpace.Space.kWorld);
                var collisionTriangles = new MIntArray();
                meshFn.getTriangles(new MIntArray(), collisionTriangles);
                for (var i = 0; i < collisionPoints.Count; i++)
                {
                    wowModel.CollisionVertices.Add(AxisInvert(collisionPoints[i]));
                    wowModel.CollisionNormals.Add(AxisInvert(collisionNormals[i]));
                }
                foreach (var vertIndex in collisionTriangles)
                {
                    wowModel.CollisionTriangles.Add((ushort)vertIndex);
                }

                collisionFound = true;
            }
        }
Пример #6
0
        private static void unpackDynMesh(Mesh dynMesh, out MIntArray faceCnx, out MFloatPointArray verticies, out MIntArray faceVtxCt)
        {
            MIntArray        m_faceCnx   = new MIntArray();
            MFloatPointArray m_verticies = new MFloatPointArray();
            MIntArray        m_faceVtxCt = new MIntArray();

            MFloatPoint vtxToAdd = new MFloatPoint();


            foreach (var vtx in dynMesh.VertexPositions)
            {
                if (MGlobal.isZAxisUp)
                {
                    vtxToAdd.x = (float)vtx.X;
                    vtxToAdd.y = (float)vtx.Y;
                    vtxToAdd.z = (float)vtx.Z;
                }
                else
                {
                    vtxToAdd.x = (float)vtx.X;
                    vtxToAdd.y = (float)vtx.Z;
                    vtxToAdd.z = -(float)vtx.Y;
                }

                m_verticies.Add(vtxToAdd);
            }

            foreach (var fidx in dynMesh.FaceIndices)
            {
                int vtxCt = (int)fidx.Count;
                m_faceVtxCt.Add(vtxCt);
                if (vtxCt == 3)
                {
                    m_faceCnx.Add((int)fidx.A);
                    m_faceCnx.Add((int)fidx.B);
                    m_faceCnx.Add((int)fidx.C);
                }
                else
                {
                    m_faceCnx.Add((int)fidx.A);
                    m_faceCnx.Add((int)fidx.B);
                    m_faceCnx.Add((int)fidx.C);
                    m_faceCnx.Add((int)fidx.D);
                }
            }

            verticies = m_verticies;
            faceCnx   = m_faceCnx;
            faceVtxCt = m_faceVtxCt;
        }
Пример #7
0
       public MObject ConvertMeshMaya(TriMesh triMesh)
       {
          MFnMesh meshMaya = new MFnMesh();

          int verticeNum = triMesh.Vertices.Count;
          MFloatPointArray points = new MFloatPointArray();
         
          for(int i=0;i<verticeNum;i++)
          {
              float x=(float)triMesh.Vertices[i].Traits.Position.x;
              float y=(float)triMesh.Vertices[i].Traits.Position.y;
              float z=(float)triMesh.Vertices[i].Traits.Position.z;

              MFloatPoint vertex = new MFloatPoint(x,y,z);
              points.append(vertex);
          }

           
           int faceNum = triMesh.Faces.Count;

           int[] face_Counts=new int[faceNum];
           for(int i=0;i<faceNum;i++)
           {
              face_Counts[i]=3;
           }
           MIntArray faceCounts = new MIntArray(face_Counts);


           int[] faceTopology=new int[faceNum*3];
            
           for(int j=0;j<faceNum ;j++)
           {
              int index=j*3;
              faceTopology[index]=triMesh.Faces[j].GetVertex(0).Index ;
               
              faceTopology[index+1]=triMesh.Faces[j].GetVertex(1).Index ;
               
              faceTopology[index+2]=triMesh.Faces[j].GetVertex(2).Index ;
               
           }

           MIntArray faceConnects = new MIntArray(faceTopology);

           MObject mesh= meshMaya.create(verticeNum, faceNum, points, faceCounts, faceConnects);

           return mesh;
       }
Пример #8
0
        public MObject ConvertMeshMaya(TriMesh triMesh)
        {
            MFnMesh meshMaya = new MFnMesh();

            int verticeNum          = triMesh.Vertices.Count;
            MFloatPointArray points = new MFloatPointArray();

            for (int i = 0; i < verticeNum; i++)
            {
                float x = (float)triMesh.Vertices[i].Traits.Position.x;
                float y = (float)triMesh.Vertices[i].Traits.Position.y;
                float z = (float)triMesh.Vertices[i].Traits.Position.z;

                MFloatPoint vertex = new MFloatPoint(x, y, z);
                points.append(vertex);
            }


            int faceNum = triMesh.Faces.Count;

            int[] face_Counts = new int[faceNum];
            for (int i = 0; i < faceNum; i++)
            {
                face_Counts[i] = 3;
            }
            MIntArray faceCounts = new MIntArray(face_Counts);


            int[] faceTopology = new int[faceNum * 3];

            for (int j = 0; j < faceNum; j++)
            {
                int index = j * 3;
                faceTopology[index] = triMesh.Faces[j].GetVertex(0).Index;

                faceTopology[index + 1] = triMesh.Faces[j].GetVertex(1).Index;

                faceTopology[index + 2] = triMesh.Faces[j].GetVertex(2).Index;
            }

            MIntArray faceConnects = new MIntArray(faceTopology);

            MObject mesh = meshMaya.create(verticeNum, faceNum, points, faceCounts, faceConnects);

            return(mesh);
        }
Пример #9
0
        private static void unpackTsMesh(TSplineSurface tsMesh, out MIntArray faceCnx, out MFloatPointArray verticies, out MIntArray faceVtxCt)
        {
            MIntArray        m_faceCnx   = new MIntArray();
            MFloatPointArray m_verticies = new MFloatPointArray();
            MIntArray        m_faceVtxCt = new MIntArray();

            MFloatPoint vtxToAdd = new MFloatPoint();

            var tsMeshCompress = tsMesh.CompressIndexes();

            foreach (var vtx in tsMeshCompress.Vertices)
            {
                if (MGlobal.isZAxisUp)
                {
                    vtxToAdd.x = (float)vtx.PointGeometry.X;
                    vtxToAdd.y = (float)vtx.PointGeometry.Y;
                    vtxToAdd.z = (float)vtx.PointGeometry.Z;
                }
                else
                {
                    vtxToAdd.x = (float)vtx.PointGeometry.X;
                    vtxToAdd.y = (float)vtx.PointGeometry.Z;
                    vtxToAdd.z = -(float)vtx.PointGeometry.Y;
                }

                m_verticies.Add(vtxToAdd);
            }

            foreach (var fidx in tsMeshCompress.Faces)
            {
                int vtxCt = fidx.Vertices.Length;
                m_faceVtxCt.Add(vtxCt);

                foreach (var fVert in fidx.Vertices)
                {
                    m_faceCnx.Add(fVert.Index);
                }
            }
            verticies = m_verticies;
            faceCnx   = m_faceCnx;
            faceVtxCt = m_faceVtxCt;
        }
Пример #10
0
        public void Load(string name)
        {
            List <StaticObjectVertex> vertices = GetVertices();
            List <uint> indices = GetIndices();

            MIntArray        polygonIndexCounts = new MIntArray((uint)indices.Count / 3);
            MIntArray        polygonIndices     = new MIntArray((uint)indices.Count);
            MFloatPointArray meshVertices       = new MFloatPointArray((uint)vertices.Count);
            MFloatArray      arrayU             = new MFloatArray((uint)vertices.Count);
            MFloatArray      arrayV             = new MFloatArray((uint)vertices.Count);
            MFnMesh          mesh        = new MFnMesh();
            MDagPath         meshDagPath = new MDagPath();
            MDGModifier      modifier    = new MDGModifier();
            MFnSet           set         = new MFnSet();

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

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

            for (int i = 0; i < vertices.Count; i++)
            {
                StaticObjectVertex vertex = vertices[i];

                meshVertices[i] = new MFloatPoint(vertex.Position.X, vertex.Position.Y, vertex.Position.Z);
                arrayU[i]       = vertex.UV.X;
                arrayV[i]       = 1 - vertex.UV.Y;
            }

            //Assign mesh data
            mesh.create(vertices.Count, indices.Count / 3, meshVertices, polygonIndexCounts, polygonIndices, arrayU, arrayV, MObject.kNullObj);
            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
            MFnPartition renderPartition = MayaHelper.FindRenderPartition();

            //Create Materials
            uint startIndex = 0;

            for (int i = 0; i < this.Submeshes.Count; i++)
            {
                MFnDependencyNode   dependencyNode = new MFnDependencyNode();
                MFnLambertShader    lambertShader  = new MFnLambertShader();
                StaticObjectSubmesh submesh        = this.Submeshes[i];

                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");
                MPlug   partitionPlug = new MFnDependencyNode(shadingEngine).findPlug("partition");
                MPlug   setsPlug      = MayaHelper.FindFirstNotConnectedElement(renderPartition.findPlug("sets"));
                modifier.connect(partitionPlug, setsPlug);

                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 = (startIndex + (uint)submesh.Indices.Count) / 3;
                for (uint j = startIndex / 3; j < endIndex; j++)
                {
                    groupPolygonIndices.append((int)j);
                }
                component.addElements(groupPolygonIndices);

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

                startIndex += (uint)submesh.Indices.Count;
            }

            mesh.updateSurface();
        }
Пример #11
0
        /// <summary>
        /// Faces and vertices UVs, positions and normals.
        /// </summary>
        private static void ExtractMeshGeometry(MayaM2Mesh mesh, MDagPath meshPath, Dictionary <string, MayaM2Bone> jointMap, List <MayaM2Vertex> globalVertexList)
        {
            // ***Data Tables***
            // UV Sets
            var uvsets        = new MStringArray();
            var meshFunctions = new MFnMesh(meshPath);

            meshFunctions.getUVSetNames(uvsets);

            //Bone Weights
            var vertexWeights    = new List <MDoubleArray>();
            var influenceObjects = new MDagPathArray();

            GetMeshWeightData(vertexWeights, influenceObjects, meshPath);

            //Positions
            var positions = new MFloatPointArray();

            meshFunctions.getPoints(positions, MSpace.Space.kWorld);

            //Normals
            var normals = new MFloatVectorArray();

            meshFunctions.getVertexNormals(false, normals, MSpace.Space.kWorld);

            var polygonIter = new MItMeshPolygon(meshPath);

            while (!polygonIter.isDone)
            {
                //Divide face into triangles
                var polyMeshRelative = new MIntArray();
                polygonIter.getVertices(polyMeshRelative);
                int numTriangles;
                polygonIter.numTriangles(out numTriangles);
                for (var i = 0; i < numTriangles; i++)
                {
                    var triangle             = new MayaM2Triangle();
                    var triangleMeshRelative = new MIntArray();
                    polygonIter.getTriangle(i, new MPointArray(), triangleMeshRelative);
                    var triangleFaceRelative = GetLocalTriangle(polyMeshRelative, triangleMeshRelative);
                    for (var v = 0; v < 3; v++)
                    {
                        var meshIndex = triangleMeshRelative[v];
                        var faceIndex = triangleFaceRelative[v];

                        //Bone weights
                        var weights = new List <Tuple <MayaM2Bone, double> >();
                        for (var b = 0; b < influenceObjects.length; b++) //for each joint
                        {
                            var kJointPath = influenceObjects[b];
                            if (!kJointPath.hasFn(MFn.Type.kJoint))
                            {
                                continue;
                            }
                            Debug.Assert(b < vertexWeights[meshIndex].Count,
                                         "vertexWeights size : " + vertexWeights.Count + " " +
                                         "\njointWeights for this vertex : " + vertexWeights[meshIndex].Count);
                            //Here are a joint&weight for this vertex
                            if (vertexWeights[meshIndex][b] > Epsilon)
                            {
                                weights.Add(new Tuple <MayaM2Bone, double>(jointMap[kJointPath.fullPathName],
                                                                           vertexWeights[meshIndex][b]));
                            }
                        }

                        //Position & normals
                        var position = positions[(int)polygonIter.vertexIndex(faceIndex)];
                        var normal   = normals[(int)polygonIter.normalIndex(faceIndex)];

                        //UV coordinates
                        var uvCoordinates = new List <Tuple <float, float> >();
                        if (uvsets.length > 0 && meshFunctions.numUVs(uvsets[0]) > 0)
                        {
                            foreach (var uvset in uvsets)
                            {
                                var uvCoords = new float[2];
                                polygonIter.getUV(faceIndex, uvCoords, uvset);
                                uvCoordinates.Add(new Tuple <float, float>(uvCoords[0], uvCoords[1]));
                            }
                        }
                        var vert = VertexFactory.Create(position, normal, uvCoordinates, weights, globalVertexList);
                        triangle.Vertices.Add(vert);
                    }
                    mesh.Faces.Add(triangle);
                }
                polygonIter.next();
            }
        }
Пример #12
0
		public polyPrimitive()
		{
			iarr = new MFloatPointArray();
			pa = new MFloatPointArray();
			faceCounts = new MIntArray();
			faceConnects = new MIntArray();
			dagMod = new MDagModifier();
			MGlobal.displayInfo("test polyPrimitive.");
		}
Пример #13
0
        public static bool ToMayaOLD(Mesh MeshToSend, string name)
        {
            bool     nodeExists = false;
            MDagPath node       = null;
            Task     checkNode  = null;
            Task     mobjMesh   = null;

            try
            {
                checkNode = Task.Factory.StartNew(() => node = DMInterop.getDagNode(name));
                checkNode.Wait(500);

                nodeExists = true;
            }
            catch (Exception)
            {
                nodeExists = false;
            }
            MFnMesh mfnMesh;

            if (nodeExists)
            {
                mfnMesh = new MFnMesh(node);
            }
            else
            {
                mfnMesh = new MFnMesh();
            }

            //unpack geom
            int numVert = MeshToSend.VertexPositions.Length;
            int numPoly = MeshToSend.FaceIndices.Length;

            MIntArray        faceCnx   = new MIntArray();
            MFloatPointArray verticies = new MFloatPointArray();
            MIntArray        faceVtxCt = new MIntArray();

            MFloatPoint vtxToAdd = new MFloatPoint();

            foreach (var vtx in MeshToSend.VertexPositions)
            {
                if (MGlobal.isZAxisUp)
                {
                    vtxToAdd.x = (float)vtx.X;
                    vtxToAdd.y = (float)vtx.Y;
                    vtxToAdd.z = (float)vtx.Z;
                }
                else
                {
                    vtxToAdd.x = (float)vtx.X;
                    vtxToAdd.y = (float)vtx.Z;
                    vtxToAdd.z = -(float)vtx.Y;
                }

                verticies.Add(vtxToAdd);
            }

            foreach (var fidx in MeshToSend.FaceIndices)
            {
                int vtxCt = (int)fidx.Count;
                faceVtxCt.Add(vtxCt);
                if (vtxCt == 3)
                {
                    faceCnx.Add((int)fidx.A);
                    faceCnx.Add((int)fidx.B);
                    faceCnx.Add((int)fidx.C);
                }
                else
                {
                    faceCnx.Add((int)fidx.A);
                    faceCnx.Add((int)fidx.B);
                    faceCnx.Add((int)fidx.C);
                    faceCnx.Add((int)fidx.D);
                }
            }

            //create maya mesh
            if (nodeExists)
            {
                mfnMesh.createInPlace(numVert, numPoly, verticies, faceVtxCt, faceCnx);
                mfnMesh.Dispose();
            }
            else
            {
                using (var obj = mfnMesh.create(numVert, numPoly, verticies, faceVtxCt, faceCnx))
                {
                    MFnDependencyNode nodeFn = new MFnDagNode(obj);
                    nodeFn.setName(name);
                    MGlobal.executeCommand("sets -e -forceElement initialShadingGroup " + nodeFn.name);
                    mfnMesh.Dispose();
                }
            }


            return(true);
        }
Пример #14
0
        private void dynMeshToMayaMesh(string name, Mesh dynMesh = null, TSplineSurface tsMesh = null)
        {
            bool     nodeExists = false;
            MDagPath node       = null;
            Task     unpackTask = null;
            Task     mobjTask   = null;

            try
            {
                node       = DMInterop.getDagNode(name);
                nodeExists = true;
            }
            catch (Exception)
            {
                nodeExists = false;
            }

            MIntArray        faceCnx   = new MIntArray();
            MFloatPointArray verticies = new MFloatPointArray();
            MIntArray        faceVtxCt = new MIntArray();
            int numVert = 0;
            int numPoly = 0;

            if (dynMesh != null)
            {
                numVert    = dynMesh.VertexPositions.Length;
                numPoly    = dynMesh.FaceIndices.Length;
                unpackTask = Task.Factory.StartNew(() => unpackDynMesh(dynMesh, out faceCnx, out verticies, out faceVtxCt));
                unpackTask.Wait(4000);
            }

            if (tsMesh != null)
            {
                numVert    = tsMesh.VerticesCount;
                numPoly    = tsMesh.FacesCount;
                unpackTask = Task.Factory.StartNew(() => unpackTsMesh(tsMesh, out faceCnx, out verticies, out faceVtxCt));
                unpackTask.Wait(4000);
            }



            if (nodeExists)
            {
                try
                {
                    meshFn = new MFnMesh(node);
                    meshFn.createInPlace(numVert, numPoly, verticies, faceVtxCt, faceCnx);
                }
                catch (Exception e)
                {
                    MGlobal.displayWarning(e.Message);
                }
            }
            else
            {
                try
                {
                    dagMod = new MDagModifier();
                    // Create a mesh data wrapper to hold the new geometry.
                    MFnMeshData dataFn      = new MFnMeshData();
                    MObject     dataWrapper = dataFn.create();

                    // Create the mesh geometry and put it into the wrapper.
                    meshFn = new MFnMesh();
                    MObject dataObj   = meshFn.create(numVert, numPoly, verticies, faceVtxCt, faceCnx, dataWrapper);
                    MObject transform = dagMod.createNode("mesh", MObject.kNullObj);

                    dagMod.doIt();

                    renameNodes(transform, name);
                    dagMod.doIt();
                    assignShadingGroup(transform, "initialShadingGroup");
                    dagMod.doIt();
                    setMeshData(transform, dataWrapper);
                }
                catch (Exception e)
                {
                    MGlobal.displayWarning(e.Message);
                }
            }

            //GC.Collect();
            //GC.WaitForPendingFinalizers();
        }
Пример #15
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();
            }
        }