public static Dictionary <string, object> getSmoothMesh(MFnMesh mayaMesh)
        {
            MObject     tempMesh = new MObject();
            MFnMeshData meshData = new MFnMeshData();
            MObject     dataObject;
            MObject     smoothedObj = new MObject();

            dataObject  = meshData.create();
            smoothedObj = mayaMesh.generateSmoothMesh(dataObject);
            MFnMesh meshFn = new MFnMesh(smoothedObj);


            // var smoothMeshObj = mayaMesh.generateSmoothMesh();


            // MFnDependencyNode mfnDn = new MFnDependencyNode(smoothedObj);
            // var meshDag = DMInterop.getDagNode(mfnDn.name);
            Mesh dynamoMesh = DMMesh.MTDMeshFromMayaMesh(meshFn, MSpace.Space.kObject);

            //MGlobal.displayInfo(smoothedObj.apiTypeStr);

            //MGlobal.deleteNode(smoothedObj);


            return(new Dictionary <string, object>
            {
                { "mesh", dynamoMesh },
                { "mayaMesh", meshFn }
            });
        }
Esempio n. 2
0
        //======================================================================
        //
        // Check the parsed arguments and do/undo/redo the command as appropriate
        //
        void checkArgs(ref MArgDatabase argsDb)
        {
            MSelectionList objects = new MSelectionList();

            argsDb.getObjects(objects);

            for (uint i = 0; i < objects.length; ++i)
            {
                MDagPath dagPath = new MDagPath();
                objects.getDagPath((uint)i, dagPath);
                MFnDagNode dagNode = new MFnDagNode(dagPath.node);
                MObject    obj     = dagNode.child(0);
                if (obj.apiTypeStr == "kMesh")
                {
                    fMesh         = new MFnMesh(obj);
                    fObj          = obj;
                    fObjTransform = dagPath.node;
                }
            }

            if (fMesh == null || fObj == null || fObjTransform == null)
            {
                string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError);
                throw new ArgumentException(errMsg, "argsDb");
            }
        }
Esempio n. 3
0
        private static void ExtractStandardMeshes(List <MayaM2Mesh> meshList, Dictionary <string, MayaM2Bone> jointMap, List <MayaM2Vertex> globalVertexList)
        {
            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
                }
                var mesh = new MayaM2Mesh();
                ExtractMeshGeometry(mesh, meshPath, jointMap, globalVertexList);
                ExtractMeshShaders(mesh, meshPath);
                meshList.Add(mesh);
            }
        }
Esempio n. 4
0
        public void ConvertToTriMesh()
        {
            MFnMesh fnMesh = GetFirstMesh();
            TriMesh mesh   = ConvertTriMesh(fnMesh);

            GlobalData.Instance.TriMesh = mesh;
        }
Esempio n. 5
0
        void Instance_Changed(object sender, EventArgs e)
        {
            MGlobal.displayInfo("update!!!\n");
            MFnMesh fnMesh = GetFirstMesh();

            UpdateMeshMaya(fnMesh, GlobalData.Instance.TriMesh);
        }
Esempio n. 6
0
        private static List <Material> GetMaterialsMesh(ref MFnMesh Mesh, ref MDagPath Path)
        {
            // Get materials for this mesh
            var Result = new List <Material>();

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

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

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

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

            return(Result);
        }
Esempio n. 7
0
        public static ShapeData GetMaterialsOfDag(MDagPath dag)
        {
            if (dag == null)
            {
                Debug.Log("dag null");
            }
            dag.extendToShape();
            MFnDependencyNode dn = new MFnDependencyNode(dag.node);
            //Debug.Log(dn.absoluteName);
            //dn.findPlug("connectAttr pCubeShape3.instObjGroups[0] blinn2SG.dagSetMembers[1]");
            MFnMesh mesh = new MFnMesh(dag);

            //int instanceCount = (int)shapeNode.instanceCount(false);
            //Debug.Log("dn instanceCount:" + instanceCount);
            uint instanceNumber = dag.instanceNumber;

            Debug.Log("dag instanceNumber:" + instanceNumber);

            MObjectArray sets = new MObjectArray(), comps = new MObjectArray();

            mesh.getConnectedSetsAndMembers(instanceNumber, sets, comps, true);


            List <string> sgList = new List <string>();

            for (int i = 0; i < sets.length; ++i)
            {
                MFnDependencyNode fnDepSGNode = new MFnDependencyNode(sets[i]);
                sgList.Add(fnDepSGNode.absoluteName);
                //Debug.Log(fnDepSGNode.name);
            }
            //Debug.Log("sgList Count:" + sgList.Count);
            return(new ShapeData(mesh, dag, sgList));
        }
Esempio n. 8
0
        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If the 3D view was selected
            if (tabControl1.SelectedIndex == 2)
            {
                // Clear the 3D view
                this.Root.Children.Clear();

                if (this.Root.Children.Count > 0)
                {
                    this.Root.Children.RemoveAt(0);
                }

                // If it's a mesh, display it
                var selected = GetFirstSelected();

                // The reason why there might not be a selection is if some tool isn't closed
                // and prevent the previous selection command from going through
                if (selected != null)
                {
                    if (selected.node.apiTypeStr == "kMesh")
                    {
                        var mesh = new MFnMesh(selected);

                        // This can take some time, so change the cursor
                        Cursor c = this.Cursor;
                        this.Cursor = Cursors.Wait;
                        this.Root.Children.Add(MakeVisualModel(mesh));
                        this.Cursor = c;
                    }
                }
            }

            e.Handled = true;
        }
        public static List <List <Point> > getFaceVerticies(MFnMesh mayaMesh)
        {
            List <List <Point> > faces = new List <List <Point> >(mayaMesh.numVertices);
            PointList            verts;
            MPointArray          mayaVerts = new MPointArray();
            MIntArray            ids       = new MIntArray();

            mayaMesh.getPoints(mayaVerts, MSpace.Space.kWorld);


            for (int i = 0; i < mayaMesh.numPolygons; i++)
            {
                mayaMesh.getPolygonVertices(i, ids);
                verts = new PointList(ids.Count);

                foreach (var vtxid in ids)
                {
                    if (MGlobal.isZAxisUp)
                    {
                        verts.Add(Point.ByCoordinates(mayaVerts[vtxid].x, mayaVerts[vtxid].y, mayaVerts[vtxid].z));
                    }
                    else
                    {
                        verts.Add(Point.ByCoordinates(mayaVerts[vtxid].x, -mayaVerts[vtxid].z, mayaVerts[vtxid].y));
                    }
                }
                faces.Add(verts);
            }

            return(faces);
        }
Esempio n. 10
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. 11
0
        public ModelVisual3D MakeVisualModel(MFnMesh mesh)
        {
            var r = new ModelVisual3D();

            r.Content = MakeModel(mesh);
            return(r);
        }
        public static List <Vector> getFaceNormals(MFnMesh mayaMesh)
        {
            List <Vector> normals = new List <Vector>(mayaMesh.numPolygons);

            MVector norm = new MVector();


            for (int i = 0; i < mayaMesh.numPolygons; i++)
            {
                mayaMesh.getPolygonNormal(i, norm, MSpace.Space.kWorld);

                if (MGlobal.isZAxisUp)
                {
                    normals.Add(Vector.ByCoordinates(norm.x, norm.y, norm.z));
                }
                else
                {
                    normals.Add(Vector.ByCoordinates(norm.x, -norm.z, norm.y));
                }
            }



            return(normals);
        }
Esempio n. 13
0
        public static Mesh ToDynamoElement(MFnMesh mMesh, string space)
        {
            MSpace.Space mspace = MSpace.Space.kWorld;
            Enum.TryParse(space, out mspace);

            return(MTDMeshFromMayaMesh(mMesh, mspace));
        }
Esempio n. 14
0
		//======================================================================
		//
		// Check the parsed arguments and do/undo/redo the command as appropriate
		//
		void checkArgs(ref MArgDatabase argsDb)
		{
			MSelectionList objects = new MSelectionList();

            argsDb.getObjects(objects);

			for (uint i = 0; i < objects.length; ++i)
			{
                MDagPath dagPath = new MDagPath();
                objects.getDagPath((uint)i, dagPath);
                MFnDagNode dagNode = new MFnDagNode(dagPath.node);
                MObject obj = dagNode.child(0);
                if (obj.apiTypeStr == "kMesh")
                {
                    fMesh = new MFnMesh(obj);
                    fObj = obj;
                    fObjTransform = dagPath.node;
                }
			}

			if( fMesh == null || fObj == null || fObjTransform == null )
			{
				string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError);
				throw new ArgumentException(errMsg, "argsDb");
			}
		}
Esempio n. 15
0
        public ModelVisual3D MakeVisualModel(MDagPath path)
        {
            var mesh = new MFnMesh(path);
            var r    = new ModelVisual3D();

            r.Content   = MakeModel(mesh);
            r.Transform = new Transform3DGroup();
            Transform3DGroup transformGroup = r.Transform as Transform3DGroup;

            MTransformationMatrix matrix = new MTransformationMatrix(path.inclusiveMatrix);
            //MVector tr =matrix.getTranslation (MSpace.Space.kWorld) ;
            //TranslateTransform3D translation =new TranslateTransform3D (tr.x, tr.y, tr.z) ;
            //transformGroup.Children.Add (translation) ;

            //double x =0, y =0, z =0, w =0 ;
            //matrix.getRotationQuaternion (ref x, ref y, ref z, ref w, MSpace.Space.kWorld) ;
            //QuaternionRotation3D rotation =new QuaternionRotation3D (new Quaternion (x, y, z, w)) ;
            //transformGroup.Children.Add (new RotateTransform3D (rotation)) ;

            //double [] scales =new double [3] ;
            //matrix.getScale (scales, MSpace.Space.kWorld) ;
            //ScaleTransform3D scale =new ScaleTransform3D (scales [0], scales [1], scales [2]) ;
            //transformGroup.Children.Add (scale) ;

            MMatrix  mat      = matrix.asMatrixProperty;
            Matrix3D matrix3d = new Matrix3D(mat [0, 0], mat [0, 1], mat [0, 2], mat [0, 3],
                                             mat [1, 0], mat [1, 1], mat [1, 2], mat [1, 3],
                                             mat [2, 0], mat [2, 1], mat [2, 2], mat [2, 3],
                                             mat [3, 0], mat [3, 1], mat [3, 2], mat [3, 3]);
            MatrixTransform3D matrixTransform = new MatrixTransform3D(matrix3d);

            transformGroup.Children.Add(matrixTransform);

            return(r);
        }
Esempio n. 16
0
        /// <summary>
        /// Extract geometry (position, normal, UVs...) for a specific vertex
        /// </summary>
        /// <param name="mFnMesh"></param>
        /// <param name="polygonId">The polygon (face) to examine</param>
        /// <param name="vertexIndexGlobal">The object-relative (mesh-relative/global) vertex index</param>
        /// <param name="vertexIndexLocal">The face-relative (local) vertex id to examine</param>
        /// <param name="hasUV"></param>
        /// <returns></returns>
        private GlobalVertex ExtractVertex(MFnMesh mFnMesh, int polygonId, int vertexIndexGlobal, int vertexIndexLocal, bool hasUV)
        {
            MPoint point = new MPoint();

            mFnMesh.getPoint(vertexIndexGlobal, point);

            MVector normal = new MVector();

            mFnMesh.getFaceVertexNormal(polygonId, vertexIndexGlobal, normal);

            // Switch coordinate system at object level
            point.z  *= -1;
            normal.z *= -1;

            var vertex = new GlobalVertex
            {
                BaseIndex = vertexIndexGlobal,
                Position  = point.toArray(),
                Normal    = normal.toArray()
            };

            // UV
            if (hasUV)
            {
                float u = 0, v = 0;
                mFnMesh.getPolygonUV(polygonId, vertexIndexLocal, ref u, ref v);
                vertex.UV = new float[] { u, v };
            }

            return(vertex);
        }
        public static List <Curve> getSmothMeshEdges(MFnMesh mayaMesh, bool createInMaya = false)
        {
            //MCommandResult result = new MCommandResult();
            int          ne           = mayaMesh.numEdges;
            MFnTransform group        = new MFnTransform();
            List <Curve> curveObjects = new List <Curve>(ne);
            MStringArray resultStr    = new MStringArray();

            var    fullName      = mayaMesh.fullPathName.Split('|');
            string transformName = fullName[fullName.Length - 2];


            if (createInMaya)
            {
                for (int i = 0; i < ne; i++)
                {
                    using (MCommandResult result = new MCommandResult())
                    {
                        MGlobal.executeCommand(
                            $"polyToCurve -name {transformName}Curves -form 2 -degree 3 -conformToSmoothMeshPreview 1 {transformName}.e[{i}]",
                            result);
                        result.getResult(resultStr);
                        curveObjects.Add(
                            DMCurve.CurveFromMfnNurbsCurveFromName(resultStr[0],
                                                                   MSpace.Space.kPostTransform.ToString()));
                    }
                }
            }
            else
            {
                //Parallel.For(0, ne, i => {
                for (int i = 0; i < ne; i++)
                {
                    using (MCommandResult result = new MCommandResult())
                    {
                        MGlobal.executeCommand(
                            $"polyToCurve -name deleteMe11232204332AA -form 2 -degree 3 -conformToSmoothMeshPreview 1 {transformName}.e[{i}]",
                            result);
                        result.getResult(resultStr);
                        curveObjects.Add(
                            DMCurve.CurveFromMfnNurbsCurveFromName(resultStr[0],
                                                                   MSpace.Space.kPostTransform.ToString()));
                        try
                        {
                            MGlobal.deleteNode(DMInterop.getDependNode(resultStr[0]));
                        }
                        catch
                        {
                            MGlobal.displayWarning("getSmothMeshEdges: unable to delete temp object");
                        }
                    }
                }

                // });
            }


            return(curveObjects);
        }
Esempio n. 18
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();
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Extract ordered indices on a triangle basis
        /// Extract position and normal of each vertex per face
        /// </summary>
        /// <param name="mFnMesh"></param>
        /// <param name="vertices"></param>
        /// <param name="indices"></param>
        /// <param name="subMeshes"></param>
        /// <param name="optimizeVertices"></param>
        private void ExtractGeometry(MFnMesh mFnMesh, List <GlobalVertex> vertices, List <int> indices, List <BabylonSubMesh> subMeshes, bool optimizeVertices)
        {
            // TODO - Multimaterials: create a BabylonSubMesh per submaterial
            // TODO - optimizeVertices
            MIntArray triangleCounts    = new MIntArray();
            MIntArray trianglesVertices = new MIntArray();

            mFnMesh.getTriangles(triangleCounts, trianglesVertices);

            // For each polygon of this mesh
            for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++)
            {
                MIntArray verticesId  = new MIntArray();
                int       nbTriangles = triangleCounts[polygonId];

                // For each triangle of this polygon
                for (int triangleIndex = 0; triangleIndex < triangleCounts[polygonId]; triangleIndex++)
                {
                    int[] triangleVertices = new int[3];
                    mFnMesh.getPolygonTriangleVertices(polygonId, triangleIndex, triangleVertices);

                    // Inverse winding order
                    var tmp = triangleVertices[1];
                    triangleVertices[1] = triangleVertices[2];
                    triangleVertices[2] = tmp;

                    // For each vertex of this triangle (3 vertices per triangle)
                    foreach (int vertexId in triangleVertices)
                    {
                        MPoint point = new MPoint();
                        mFnMesh.getPoint(vertexId, point);

                        MVector normal = new MVector();
                        mFnMesh.getFaceVertexNormal(polygonId, vertexId, normal);

                        var vertex = new GlobalVertex
                        {
                            BaseIndex = vertexId,
                            Position  = point.toArray(),
                            Normal    = normal.toArray()
                        };

                        indices.Add(vertices.Count);
                        vertices.Add(vertex);
                    }
                }
            }

            // BabylonSubMesh
            var subMesh = new BabylonSubMesh {
                indexStart = 0, materialIndex = 0
            };

            subMeshes.Add(subMesh);

            subMesh.indexCount    = indices.Count;
            subMesh.verticesStart = 0;
            subMesh.verticesCount = vertices.Count;
        }
Esempio n. 20
0
        //======================================================================
        //
        // Look through the arg database and verify that the arguments are
        // valid. Only checks the common flags so derived classes should call
        // this parent method first before checking their own flags.
        //
        public virtual void checkArgs(MArgDatabase argsDb)
        {
            String formatType = "raw";

            fSerialize = AssociationsSerializer.formatByName(formatType);
            if (fSerialize == null)
            {
                String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kMetadataFormatNotFound);
                String msg = String.Format(fmt, formatType);
                displayError(msg);
                throw new System.ArgumentException(msg);
            }

            //----------------------------------------
            // (selection list)
            //
            // Commands need at least one mesh object on which to operate so gather up
            // the list of meshes specified and/or selected.
            //

            // Empty out the list of meshes on which to operate so that it can be
            // populated from the selection or specified lists.
            fMeshes.clear();

            MSelectionList objects = new MSelectionList();

            argsDb.getObjects(objects);
            for (int i = 0; i < objects.length; ++i)
            {
                MDagPath dagPath = new MDagPath();
                objects.getDagPath((uint)i, dagPath);

                MFnDagNode dagNode = new MFnDagNode(dagPath.node);
                MObject    obj     = dagNode.child(0);
                if (obj.apiTypeStr == "kMesh")
                {
                    MFnMesh mesh = new MFnMesh(obj);
                    if (mesh != null)
                    {
                        fMeshes.append(obj);
                    }
                }
                else
                {
                    String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError);
                    String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]");
                    displayError(msg);
                    throw new System.InvalidOperationException(msg);
                }
            }

            if (fMeshes.length == 0)
            {
                String msg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError);
                displayError(msg);
                throw new System.InvalidOperationException(msg);
            }
        }
Esempio n. 21
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);
        }
Esempio n. 22
0
        public static bool ContainsHoles(this MFnMesh mesh)
        {
            MIntArray holeInfoArray   = new MIntArray();
            MIntArray holeVertexArray = new MIntArray();

            mesh.getHoles(holeInfoArray, holeVertexArray);

            return(holeInfoArray.length != 0);
        }
Esempio n. 23
0
 // Utility to create a 3D model our of Maya's meshes
 public MeshGeometry3D MakeGeometry(MFnMesh fnMesh)
 {
     var r = new MeshGeometry3D();
     var mesh = new TriangleMeshAdapater(fnMesh);
     r.Positions = mesh.Points;
     r.TriangleIndices = mesh.Indices;
     r.Normals = mesh.Normals;
     return r;
 }
        public static List <List <Curve> > getSmothMeshEdgesPerFace(MFnMesh mayaMesh, bool createInMaya = false)
        {
            MCommandResult ptcResult = new MCommandResult();
            MCommandResult teResult  = new MCommandResult();

            int numPoly = mayaMesh.numPolygons;

            List <List <Curve> > curveObjects    = new  List <List <Curve> >(numPoly);
            MStringArray         ptcResultStr    = new MStringArray();
            MStringArray         teResultStr     = new MStringArray();
            MStringArray         teResultStrFlat = new MStringArray();

            List <Curve> tempCurveArray = null;

            if (createInMaya)
            {
            }
            else
            {
                for (int i = 0; i < numPoly; i++)
                {
                    MGlobal.executeCommand($"polyListComponentConversion -te {mayaMesh.name}.f[{i}]", teResult);
                    teResult.getResult(teResultStr);
                    MGlobal.clearSelectionList();

                    foreach (var ters in teResultStr)
                    {
                        MGlobal.selectByName(ters, MGlobal.ListAdjustment.kAddToList);
                    }
                    MGlobal.executeCommand($"ls -sl -fl", teResult);
                    teResult.getResult(teResultStrFlat);

                    tempCurveArray = new List <Curve>((int)teResultStrFlat.length);

                    foreach (var e in teResultStrFlat)
                    {
                        MGlobal.executeCommand($"polyToCurve -name deleteMe11232204332AA -form 2 -degree 3 -conformToSmoothMeshPreview 1 {e}", ptcResult);
                        ptcResult.getResult(ptcResultStr);
                        tempCurveArray.Add(DMCurve.CurveFromMfnNurbsCurveFromName(ptcResultStr[0], MSpace.Space.kPostTransform.ToString()));
                        try
                        {
                            MGlobal.deleteNode(DMInterop.getDependNode(ptcResultStr[0]));
                        }
                        catch
                        {
                            MGlobal.displayWarning("getSmothMeshEdges: unable to delete temp object");
                        }
                    }

                    curveObjects.Add(tempCurveArray);
                }
            }


            return(curveObjects);
        }
Esempio n. 25
0
 public void UpdateMeshMaya(MFnMesh fnMesh, TriMesh triMesh)
 {
     for (int i = 0; i < triMesh.Vertices.Count; i++)
     {
         MPoint pos = new MPoint(triMesh.Vertices[i].Traits.Position.x,
                                 triMesh.Vertices[i].Traits.Position.y,
                                 triMesh.Vertices[i].Traits.Position.z);
         fnMesh.setPoint(i, pos);
     }
 }
Esempio n. 26
0
        // Utility to create a 3D model our of Maya's meshes
        public MeshGeometry3D MakeGeometry(MFnMesh fnMesh)
        {
            var r    = new MeshGeometry3D();
            var mesh = new TriangleMeshAdapater(fnMesh);

            r.Positions       = mesh.Points;
            r.TriangleIndices = mesh.Indices;
            r.Normals         = mesh.Normals;
            return(r);
        }
Esempio n. 27
0
        public override void doCreate()
        {
            Associations associationsRead = null;
            MIStream     inStream         = MStreamUtils.CreateIFStream(fileName);
            string       errors           = "";

            associationsRead = fSerialize.read(inStream, ref errors);
            if (associationsRead == null)
            {
                String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kImportMetadataFileReadFailed);
                String msg;
                if (errors == null || errors.Length < 1)
                {
                    errors = "No errors was given by the serializer when reading the metadata file.";
                }
                msg = String.Format(fmt, fileName, errors);
                displayError(msg);
                throw new System.ApplicationException(msg);
            }

            String resultFmt = MStringResource.getString(MetaDataRegisterMStringResources.kImportMetadataResult);

            for (int i = 0; i < fMeshes.length; ++i)
            {
                MFnMesh mesh = new MFnMesh(fMeshes[i]);
                // Should have filtered out non-meshes already but check anyway
                if (mesh == null)
                {
                    continue;
                }

                displayInfo(mesh.fullPathName);
                //We dont have the correct interface on MDGModifier to assign metadata so no undo redo for now
                Associations associationsMesh = mesh.metadata;
                associationsMesh.assign(associationsRead);

                for (int c = 0; c < associationsRead.channelCount; ++c)
                {
                    Autodesk.Maya.MetaData.Channel channel = associationsRead.channelAt((uint)c);
                    String cName = channel.nameProperty;
                    for (int s = 0; s < channel.dataStreamCount; ++s)
                    {
                        Autodesk.Maya.MetaData.Stream cStream = channel.dataStream((uint)s);
                        if (cStream != null)
                        {
                            String sName = cStream.name;
                            String msg   = String.Format(resultFmt, mesh.fullPathName, cName, sName);
                            appendToResult(msg);
                        }
                    }
                }
            }
            MStreamUtils.Close(inStream);
            inStream = null;
        }
Esempio n. 28
0
        public static MFnMesh GetMayaMesh(string dagName, string space)
        {
            MDagPath dagPath = DMInterop.getDagNode(dagName);

            MSpace.Space mspace = MSpace.Space.kWorld;
            Enum.TryParse(space, out mspace);

            MFnMesh mayaMesh = new MFnMesh(dagPath);

            return(mayaMesh);
        }
Esempio n. 29
0
 public void UpdateTriMesh(MFnMesh fnMesh, TriMesh triMesh)
 {
     for (int i = 0; i < triMesh.Vertices.Count; i++)
     {
         MPoint pos = new MPoint();
         fnMesh.getPoint(i, pos);
         triMesh.Vertices[i].Traits.Position.x = pos.x;
         triMesh.Vertices[i].Traits.Position.y = pos.y;
         triMesh.Vertices[i].Traits.Position.z = pos.z;
     }
 }
Esempio n. 30
0
        private void computeMeshData()
        {
            foreach (MayaMesh mesh in allMeshes)
            {
                // Get the Maya mesh
                MFnMesh mayaMesh = new MFnMesh(mesh.mayaObjectPath);

                // Does the maya mesh have UVs?
                MStringArray uvSetNames = new MStringArray();
                mayaMesh.getUVSetNames(uvSetNames);
                bool hasUvs = (uvSetNames.length > 0) && (mayaMesh.numUVs(uvSetNames[0]) > 0);

                // Iterate through all of the vertices and build the data.
                MItMeshFaceVertex it = new MItMeshFaceVertex(mesh.mayaObjectPath);
                while (!it.isDone)
                {
                    // Create a new vertex and populate its data.
                    Vertex vert = new Vertex();

                    // Get the local position relative to the world origin.
                    MPoint mayaPos = it.position(MSpace.Space.kObject);
                    vert.position = new Vector3((float)mayaPos.x, (float)mayaPos.y, (float)mayaPos.z);
                    //vert.position = new Vector3((float)mayaPos.x - mesh.sourceXForm.mayaWorldPosition.x,
                    //(float)mayaPos.y - mesh.sourceXForm.mayaWorldPosition.y,
                    //(float)mayaPos.z - mesh.sourceXForm.mayaWorldPosition.z);

                    // Get the normal.
                    MVector mayaNrm = new MVector();
                    it.getNormal(mayaNrm, MSpace.Space.kObject);
                    vert.normal = new Vector3((float)mayaNrm.x, (float)mayaNrm.y, (float)mayaNrm.z);

                    // Texcoords.
                    if (hasUvs && it.hasUVsProperty)
                    {
                        float[] mayaUvs = new float[2];
                        it.getUV(mayaUvs, uvSetNames[0]);
                        vert.texcoord = new Vector2(mayaUvs[0], mayaUvs[1]);
                    }

                    // Append the vertex.
                    mesh.vertices.Add(vert);
                    it.next();
                }

                // Get all index data.
                MIntArray mia1 = new MIntArray();
                MIntArray mia2 = new MIntArray();
                mayaMesh.getTriangleOffsets(mia1, mia2);
                foreach (int idx in mia2)
                {
                    mesh.indices.Add((uint)idx);
                }
            }
        }
Esempio n. 31
0
        public static MDagPath DuplicateMesh(MDagPath targetDag)
        {
            if (targetDag == null)
            {
                return(null);
            }
            MFnMesh newMesh = new MFnMesh();

            targetDag.extendToShape();
            return(MDagPath.getAPathTo(newMesh.copy(targetDag.node)));
        }
Esempio n. 32
0
        //======================================================================
        //
        // Look through the arg database and verify that the arguments are
        // valid. Only checks the common flags so derived classes should call
        // this parent method first before checking their own flags.
        //
        public virtual void checkArgs(MArgDatabase argsDb)
        {
            String formatType = "raw";
            fSerialize = AssociationsSerializer.formatByName( formatType );
            if( fSerialize == null)
            {
                String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kMetadataFormatNotFound);
                String msg = String.Format(fmt, formatType);
                displayError(msg);
                throw new System.ArgumentException(msg);
            }

            //----------------------------------------
            // (selection list)
            //
            // Commands need at least one mesh object on which to operate so gather up
            // the list of meshes specified and/or selected.
            //

            // Empty out the list of meshes on which to operate so that it can be
            // populated from the selection or specified lists.
            fMeshes.clear();

            MSelectionList objects = new MSelectionList();
            argsDb.getObjects(objects);
            for (int i = 0; i<objects.length; ++i)
            {
                MDagPath dagPath = new MDagPath();
                objects.getDagPath((uint)i, dagPath);

                MFnDagNode dagNode = new MFnDagNode( dagPath.node );
                MObject obj = dagNode.child(0);
                if (obj.apiTypeStr == "kMesh")
                {
                    MFnMesh mesh = new MFnMesh(obj);
                    if(mesh != null)
                        fMeshes.append(obj);
                }
                else
                {
                    String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError);
                    String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]");
                    displayError(msg);
                    throw new System.InvalidOperationException(msg);
                }
            }

            if( fMeshes.length == 0 )
            {
                String msg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError);
                displayError(msg);
                throw new System.InvalidOperationException(msg);
            }
        }
Esempio n. 33
0
 public void UpdateTriMesh(MFnMesh fnMesh, TriMesh triMesh)
 {
     for (int i = 0; i < triMesh.Vertices.Count; i++)
     {
         MPoint pos = new MPoint();
         fnMesh.getPoint(i, pos);
         triMesh.Vertices[i].Traits.Position.x = pos.x;
         triMesh.Vertices[i].Traits.Position.y = pos.y;
         triMesh.Vertices[i].Traits.Position.z = pos.z;
     }
 }
Esempio n. 34
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;
        }
Esempio n. 35
0
        public static bool CombineMeshes(List <MFnMesh> meshes, bool smartMergeEdge = false)
        {
            for (int i = 0; i < meshes.Count; i++)
            {
                MFnMesh m = new MFnMesh();

                MIntArray vertCounts = new MIntArray(), indiceLists = new MIntArray();
                meshes[i].getVertices(vertCounts, indiceLists);
            }

            return(false);
        }
Esempio n. 36
0
        public TriangleMeshAdapater(MFnMesh mesh)
        {
            MIntArray indices = new MIntArray();
            MIntArray triangleCounts = new MIntArray();
            MPointArray points = new MPointArray();

            mesh.getTriangles(triangleCounts, indices);
            mesh.getPoints(points);

            // Get the triangle indices
            Indices = new Int32Collection((int)indices.length);
            for (int i = 0; i < indices.length; ++i)
                Indices.Add(indices[i]);

            // Get the control points (vertices)
            Points = new Point3DCollection((int)points.length);
            for (int i = 0; i < (int)points.length; ++i)
            {
                MPoint pt = points[i];
                Points.Add(new Point3D(pt.x, pt.y, pt.z));
            }

            // Get the number of triangle faces and polygon faces 
            Debug.Assert(indices.length % 3 == 0);
            int triFaces = (int)indices.length / 3;
            int polyFaces = mesh.numPolygons;

            // We have normals per polygon, we want one per triangle. 
            Normals = new Vector3DCollection(triFaces);
            int nCurrentTriangle = 0;

            // Iterate over each polygon
            for (int i = 0; i < polyFaces; ++i)
            {
                // Get the polygon normal
                var maya_normal = new MVector();
                mesh.getPolygonNormal((int)i, maya_normal);
                System.Windows.Media.Media3D.Vector3D normal = new System.Windows.Media.Media3D.Vector3D(maya_normal.x, maya_normal.y, maya_normal.z);

                // Iterate over each tri in the current polygon
                int nTrisAtFace = triangleCounts[i];
                for (int j = 0; j < nTrisAtFace; ++j)
                {
                    Debug.Assert(nCurrentTriangle < triFaces);
                    Normals.Add(normal);
                    nCurrentTriangle++;
                }
            }
            Debug.Assert(nCurrentTriangle == triFaces);
        }
Esempio n. 37
0
        public override void doCreate()
        {
            Associations associationsRead = null;
            MIStream inStream = MStreamUtils.CreateIFStream(fileName);
            string errors = "";
		    associationsRead = fSerialize.read( inStream, ref errors );
		    if( associationsRead == null)
		    {
			    String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kImportMetadataFileReadFailed);
			    String msg;
                if(errors == null || errors.Length < 1)
                {
                    errors = "No errors was given by the serializer when reading the metadata file.";
                }
                msg = String.Format(fmt, fileName, errors);
			    displayError(msg);
                throw new System.ApplicationException(msg);
		    }

            String resultFmt = MStringResource.getString(MetaDataRegisterMStringResources.kImportMetadataResult);
	        for( int i=0; i<fMeshes.length; ++i )
	        {
		        MFnMesh mesh = new MFnMesh(fMeshes[i]);
		        // Should have filtered out non-meshes already but check anyway
		        if( mesh == null ) continue;

		        displayInfo( mesh.fullPathName );
                //We dont have the correct interface on MDGModifier to assign metadata so no undo redo for now
                Associations associationsMesh = mesh.metadata;
                associationsMesh.assign(associationsRead);
		        
			    for( int c=0; c < associationsRead.channelCount; ++c )
			    {
				    Autodesk.Maya.MetaData.Channel channel = associationsRead.channelAt((uint)c);
                    String cName = channel.nameProperty;
				    for( int s=0; s<channel.dataStreamCount; ++s )
				    {
					    Autodesk.Maya.MetaData.Stream cStream = channel.dataStream((uint)s);
					    if( cStream != null)
					    {
						    String sName = cStream.name;
						    String msg = String.Format( resultFmt, mesh.fullPathName, cName, sName );
						    appendToResult( msg );
					    }
				    }
			    }
	        }
            MStreamUtils.Close(inStream);
            inStream = null;
        }
        public override void createVertexStream(MObject objPath,
            MVertexBuffer vertexBuffer,
            MComponentDataIndexing targetIndexing,
            MComponentDataIndexing sharedIndexing,
            MVertexBufferArray sourceStreams)
        {
            // get the descriptor from the vertex buffer.
            // It describes the format and layout of the stream.
            MVertexBufferDescriptor descriptor = vertexBuffer.descriptor;

            // we are expecting a float stream.
            if (descriptor.dataType != Autodesk.Maya.OpenMayaRender.MHWRender.MGeometry.DataType.kFloat) return;

            // we are expecting a float2
            if (descriptor.dimension != 2) return;

            // we are expecting a texture channel
            if (descriptor.semantic != Autodesk.Maya.OpenMayaRender.MHWRender.MGeometry.Semantic.kTexture) return;

            // get the mesh from the current path, if it is not a mesh we do nothing.
            MFnMesh mesh = null;
            try {
                mesh = new MFnMesh(objPath);
            } catch(System.Exception) {
                return; // failed
            }

            MUintArray indices = targetIndexing.indicesProperty;
            uint vertexCount = indices.length;
            if (vertexCount <= 0) return;

            unsafe {
                // acquire the buffer to fill with data.
                float * buffer = (float *)vertexBuffer.acquire(vertexCount);

                for (int i = 0; i < vertexCount; i++)
                {
                    // Here we are embedding some custom data into the stream.
                    // The included effects (vertexBufferGeneratorGL.cgfx and
                    // vertexBufferGeneratorDX11.fx) will alternate
                    // red, green, and blue vertex colored triangles based on this input.
                    *(buffer++) = 1.0f;
                    *(buffer++) = (float)indices[i]; // color index
                }

                // commit the buffer to signal completion.
                vertexBuffer.commit( (byte *)buffer);
            }
        }
Esempio n. 39
0
 public Point3DCollection receiveVertexPositionsFromMaya(string node_name)
 {
     MPlug plLocal = getPlug(node_name, "outMesh");
     MObject oOutMesh = new MObject();
     plLocal.getValue(oOutMesh);
     MFnMesh m = new MFnMesh(oOutMesh);
     MPointArray p_aVertices = new MPointArray();
     m.getPoints(p_aVertices, MSpace.Space.kWorld);
     Point3DCollection vertices = new Point3DCollection();
     foreach (MPoint p in p_aVertices)
     {
         vertices.Add(new Point3D(p.x, p.y, p.z));
     }
     return vertices;
 }
Esempio n. 40
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;
       }
Esempio n. 41
0
        public override void doCreate()
        {
            if( fMeshes.length != 1 )
            {
                throw new System.ApplicationException("ExportMetadataCmd: do not support less or more then 1 mesh.");
            }
            MFnMesh mesh = new MFnMesh( fMeshes[0] );

            displayInfo( mesh.fullPathName );

            Associations associationsToWrite = mesh.metadata;
            if( associationsToWrite == null)
            {
                throw new System.ApplicationException("ExportMetadataCmd: no association to write.");
            }

            String	errors = "";

            // Dump either to a file or the return string, depending on which was
            // requested.
            //
            MOStream destination = MStreamUtils.CreateOFStream(fileName);
            if( fSerialize.write( associationsToWrite, destination, ref errors ) == 0 )
            {
                setResult(fileName);
            }
            else
            {
                String msg = MStringResource.getString(MetaDataRegisterMStringResources.kExportMetadataFailedFileWrite);
                displayError(msg);
            }
            MStreamUtils.Close(destination);
            destination = null;

            if( errors != null && errors.Length > 0 )
            {
                displayError( errors );
                return;
            }

            return;
        }
Esempio n. 42
0
        public override bool getSourceIndexing(MObject obj, MComponentDataIndexing sourceIndexing)
		{
            // get the mesh from the current path, if it is not a mesh we do nothing.
			MFnMesh mesh = null;
			try {
				mesh = new MFnMesh(obj);
			} catch(System.Exception) {
				return false;
			}

			// if it is an empty mesh we do nothing.
			int numPolys = mesh.numPolygons;
			if (numPolys <= 0) return false;

			// for each face
            MUintArray vertToFaceVertIDs = sourceIndexing.indicesProperty;
			uint faceNum = 0;
			for (int i = 0; i < numPolys; i++)
			{
				// assign a color ID to all vertices in this face.
				uint faceColorID = faceNum % 3;

				int vertexCount = mesh.polygonVertexCount(i);
				for (int j = 0; j < vertexCount; j++)
				{
					// set each face vertex to the face color
					vertToFaceVertIDs.append(faceColorID);
				}

				faceNum++;
			}

			// assign the source indexing
			sourceIndexing.setComponentType(MComponentDataIndexing.MComponentType.kFaceVertex);

			return true;
		}
Esempio n. 43
0
        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If the 3D view was selected
            if (tabControl1.SelectedIndex == 2)
            {
                // Clear the 3D view
                this.Root.Children.Clear();

                if (this.Root.Children.Count > 0)
                    this.Root.Children.RemoveAt(0);

                // If it's a mesh, display it
                var selected = GetFirstSelected();

                // The reason why there might not be a selection is if some tool isn't closed
                // and prevent the previous selection command from going through
                if (selected != null)
                {
                    if (selected.node.apiTypeStr == "kMesh")
                    {
                        var mesh = new MFnMesh(selected);

                        // This can take some time, so change the cursor
                        Cursor c = this.Cursor;
                        this.Cursor = Cursors.Wait;
                        this.Root.Children.Add(MakeVisualModel(mesh));
                        this.Cursor = c;
                    }
                }
            }

            e.Handled = true;
        }
Esempio n. 44
0
 public ModelVisual3D MakeVisualModel(MFnMesh mesh)
 {
     var r = new ModelVisual3D();
     r.Content = MakeModel(mesh);
     return r;
 }
Esempio n. 45
0
 public Model3D MakeModel(MFnMesh mesh)
 {
     return MakeGeometryModel(MakeGeometry(mesh), MakeBlueMaterial());
 }
Esempio n. 46
0
		//======================================================================
		//
		// Do the metadata creation. The metadata will be randomly initialized
		// based on the channel type and the structure specified. For recognized
		// components the number of metadata elements will correspond to the count
		// of components in the selected mesh, otherwise a random number of metadata
		// elements between 1 and 100 will be created (at consecutive indices).
		//
		// The previously existing metadata is preserved for later undo.
		//
		override public void doIt(MArgList args)
		{
			MArgDatabase argsDb = new MArgDatabase(syntax, args);

			checkArgs(ref argsDb);

			clearResult();

			uint numNodes = fNodes.length;
			int i;
			for (i = 0; i < numNodes; ++i)
			{
                // fNodes[i] is the transform not the shape itself
                MFnDagNode dagNode = new MFnDagNode(fNodes[i]);
                MObject obj = dagNode.child(0);
                // obj is the shape, which is where we can add the meta data
				MFnDependencyNode node = new MFnDependencyNode(obj);
				// Get the current metadata (empty if none yet)
				Associations newMetadata = new Associations(node.metadata);
				Channel newChannel = newMetadata.channel(fChannelType);

				// Check to see if the requested stream name already exists
				Stream oldStream = newChannel.dataStream(fStreamName);
				if (oldStream != null)
				{

					string fmt = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataHasStream);
					string msg = String.Format(fmt, fStreamName);
					MGlobal.displayError( msg );
					continue;
				}

				Stream newStream = new Stream(fStructure, fStreamName);

                string strmName = newStream.name;

				int indexCount = 0;
                MFnMesh mesh = null;
                Random rndIndexCount = new Random();
                // Treat the channel type initializations different for meshes
				if (obj.hasFn(MFn.Type.kMesh))
				{
                    mesh = new MFnMesh(obj);
					// Get mesh-specific channel type parameters
					if (fChannelType == "face")
					{
						indexCount = mesh.numPolygons;
					}
					else if (fChannelType == "edge")
					{
						indexCount = mesh.numEdges;
					}
					else if (fChannelType == "vertex")
					{
						indexCount = mesh.numVertices;
					}
					else if (fChannelType == "vertexFace")
					{
						indexCount = mesh.numFaceVertices;
					}
					else
					{
						// Set a random number between 1 to 100
                        indexCount = rndIndexCount.Next(1, 100);
					}
				}
				else
				{
					// Create generic channel type information
                    indexCount = rndIndexCount.Next(1, 100);
				}

				// Fill specified stream ranges with random data
				int structureMemberCount = fStructure.memberCount;
				uint m,n,d;
                Random rnd = new Random();
                for (m = 0; m < indexCount; ++m)
				{
					// Walk each structure member and fill with random data
					// tailored to the member data type.
					Handle handle = new Handle(fStructure);
					for (n = 0; n < structureMemberCount; ++n)
					{
						handle.setPositionByMemberIndex(n);

						switch (handle.dataType)
						{
						case Member.eDataType.kBoolean:
							{
                                bool[] data = new bool[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									int randomInt = rnd.Next(0, 2);
									bool randomBool = randomInt == 1 ? true : false;
                                    data[d] = randomBool;
                                }
                                handle.asBooleanArray = data;
								break;
							}
						case Member.eDataType.kDouble:
							{
                                double[] data = new double[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									// Set a random number between -2000000000.0.0 and 2000000000.0.0
									data[d] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
                                }
                                handle.asDoubleArray = data;
								break;
							}
						case Member.eDataType.kDoubleMatrix4x4:
							{
                                double[] data = new double[handle.dataLength * 16];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									data[d*16+0] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+1] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+2] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+3] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+4] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+5] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+6] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+7] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+8] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+9] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+10] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+11] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+12] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+13] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+14] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+15] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
                                }
                                handle.asDoubleMatrix4x4 = data;
								break;
							}
						case Member.eDataType.kFloat:
							{
                                float[] data = new float[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
    								// Set a random number between -2000000.0 and 2000000.0
	    							data[d] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
                                }
                                handle.asFloatArray = data;
								break;
							}
						case Member.eDataType.kFloatMatrix4x4:
							{
                                float[] data = new float[handle.dataLength * 16];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									// Set a random number between -2000000.0 and 2000000.0
									data[d*16+0] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+1] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+2] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+3] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+4] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+5] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+6] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+7] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+8] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+9] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+10] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+11] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+12] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+13] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+14] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+15] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
                                }
                                handle.asFloatMatrix4x4 = data;
								break;
							}
						case Member.eDataType.kInt8:
							{
                                sbyte[] data = new sbyte[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (sbyte)rnd.Next(SByte.MinValue, SByte.MaxValue+1);
                                }
                                handle.asInt8Array = data;
								break;
							}
						case Member.eDataType.kInt16:
							{
								short[] data = new short[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (short)rnd.Next(Int16.MinValue, Int16.MaxValue+1);
                                }
                                handle.asInt16Array = data;
								break;
							}
						case Member.eDataType.kInt32:
							{
								int[] data = new int[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    // rnd.Next returns a number between [arg1,arg2[
                                    // but unfortunately I can't pass Int32.MaxValue+1 here....
                                    data[d] = rnd.Next(Int32.MinValue, Int32.MaxValue);
                                }
                                handle.asInt32Array = data;
								break;
							}
						case Member.eDataType.kInt64:
							{
								long[] data = new long[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    // rnd.Next() gives a number between [0,Int32
                                    data[d] = (long)rnd.Next(Int32.MinValue, Int32.MaxValue);
                                    if( data[d] >= 0 )
                                        data[d] *= Int64.MaxValue / Int32.MaxValue;
                                    else
                                        data[d] *= Int64.MinValue / Int32.MinValue;
                                }
                                handle.asInt64Array = data;
								break;
							}
						case Member.eDataType.kUInt8:
							{
								byte[] data = new byte[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (byte)rnd.Next(0, Byte.MaxValue + 1);
                                }
                                handle.asUInt8Array = data;
								break;
							}
						case Member.eDataType.kUInt16:
							{
								ushort[] data = new ushort[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (ushort)rnd.Next(0, UInt16.MaxValue + 1);
                                }
                                handle.asUInt16Array = data;
								break;
							}
						case Member.eDataType.kUInt32:
							{
								uint[] data = new uint[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (uint)rnd.Next();
                                }
                                handle.asUInt32Array = data;
								break;
							}
						case Member.eDataType.kUInt64:
							{
								ulong[] data = new ulong[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
    								data[d] = ((ulong)rnd.Next()) * UInt64.MaxValue / UInt32.MaxValue;
                                }
                                handle.asUInt64Array = data;
								break;
							}
						case Member.eDataType.kString:
							{
                                string[] randomStrings = new string[] { "banana", "tomatoe", "apple", "pineapple", "apricot", "pepper", "olive", "grapefruit" };
                                string[] data = new string[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    int index = rnd.Next( randomStrings.Length );
    								data[d] = randomStrings[index];
                                }
                                handle.asStringArray = data;
								break;
							}
						default:
							{
								Debug.Assert(false, "This should never happen");
								break;
							}
						}
					}
					newStream.setElement(new Index(m), handle);
				}
				newChannel.setDataStream(newStream);
				newMetadata.setChannel(newChannel);

                // Note: the following will not work if "obj" is a shape constructed by a source object
                // You need to delete the history of the shape before calling this...
                fDGModifier.setMetadata(obj, newMetadata);
                fDGModifier.doIt();

				// Set the result to the number of actual metadata values set as a
				// triple value:
				//	 	(# nodes, # metadata elements, # members per element)
				//
				MIntArray theResult = new MIntArray();
				theResult.append( (int) fNodes.length );
				theResult.append( (int) indexCount );
				theResult.append( (int) structureMemberCount );
				setResult( theResult );

			}
		}
        public override void glBind(MDagPath shapePath)
        {
            // ONLY push and pop required attributes performance reasons...
            //
            OpenGL.glPushAttrib(OpenGL.GL_LIGHTING_BIT);

            lightingOn = OpenGL.glIsEnabled(OpenGL.GL_LIGHTING);
            if (lightingOn > 0)
            {
                OpenGL.glEnable(OpenGL.GL_COLOR_MATERIAL);
                OpenGL.glColorMaterial(OpenGL.GL_FRONT_AND_BACK, OpenGL.GL_DIFFUSE);
            }

            // Base colour is always white
            OpenGL.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

            // Bind texture
            if(libOpenMayaNet.MAYA_API_VERSION >= 800)
            {
                MObject l_object =  shapePath.node;
                MFnMesh mesh = new MFnMesh(l_object);
                String uvSetName = "map1";
                MObjectArray textures = new MObjectArray();

                boundTexture = false;
                mesh.getAssociatedUVSetTextures(uvSetName, textures);
                if (textures.length > 0)
                {
                    MImageFileInfo.MHwTextureType hwType = new MImageFileInfo.MHwTextureType();
                    MHwTextureManager.glBind(textures[0], ref hwType);
                    boundTexture = true;
                }

                if( !boundTexture)
                {
                    OpenGL.glDisable(OpenGL.GL_TEXTURE_2D);
                    OpenGL.glBindTexture(OpenGL.GL_TEXTURE_2D, 0);
                }
            }
            else
            {
                // To get this code branch to compile, replace <change file name here>
                // with an appropriate file name
                if (id == 0)
                {
                    MImage fileImage = new MImage();
                    fileImage.readFromFile("<change file name here>");
                    uint[] param = new uint[1];
                    OpenGL.glGenTextures(1, param);
                    id = param[0];
                    OpenGL.glEnable(OpenGL.GL_TEXTURE_2D);
                    OpenGL.glBindTexture(OpenGL.GL_TEXTURE_2D, id);
                    unsafe
                    {
                        uint width = 0, height = 0;
                        fileImage.getSize(out width, out height);
                        byte* pPixels = fileImage.pixels();
                        OpenGL.glTexImage2D(OpenGL.GL_TEXTURE_2D,
                                            0,
                                            (int)OpenGL.GL_RGBA8,
                                            (int)width,
                                            (int)height,
                                            0,
                                            OpenGL.GL_RGBA,
                                            OpenGL.GL_UNSIGNED_BYTE,
                                            pPixels);
                    }
                }
                else
                {
                    OpenGL.glEnable(OpenGL.GL_TEXTURE_2D);
                    OpenGL.glBindTexture(OpenGL.GL_TEXTURE_2D, id);
                }
                boundTexture = true;

            }

            if( boundTexture)
            {
                OpenGL.glTexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_S, (int)OpenGL.GL_REPEAT);
                OpenGL.glTexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_T, (int)OpenGL.GL_REPEAT);
                OpenGL.glTexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, (int)OpenGL.GL_LINEAR);
                OpenGL.glTexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, (int)OpenGL.GL_LINEAR);
            }
            OpenGL.glEnableClientState(OpenGL.GL_VERTEX_ARRAY);

            return;
        }
Esempio n. 48
0
        private void computeMeshData()
        {
            foreach( MayaMesh mesh in allMeshes )
            {
                // Get the Maya mesh
                MFnMesh mayaMesh = new MFnMesh(mesh.mayaObjectPath);

                // Does the maya mesh have UVs?
                MStringArray uvSetNames = new MStringArray();
                mayaMesh.getUVSetNames(uvSetNames);
                bool hasUvs = (uvSetNames.length > 0) && (mayaMesh.numUVs(uvSetNames[0]) > 0);

                // Iterate through all of the vertices and build the data.
                MItMeshFaceVertex it = new MItMeshFaceVertex(mesh.mayaObjectPath);
                while( !it.isDone )
                {
                    // Create a new vertex and populate its data.
                    Vertex vert = new Vertex();

                    // Get the local position relative to the world origin.
                    MPoint mayaPos = it.position(MSpace.Space.kObject);
                    vert.position = new Vector3((float)mayaPos.x, (float)mayaPos.y, (float)mayaPos.z);
                    //vert.position = new Vector3((float)mayaPos.x - mesh.sourceXForm.mayaWorldPosition.x,
                                                                            //(float)mayaPos.y - mesh.sourceXForm.mayaWorldPosition.y,
                                                                            //(float)mayaPos.z - mesh.sourceXForm.mayaWorldPosition.z);

                    // Get the normal.
                    MVector mayaNrm = new MVector();
                    it.getNormal(mayaNrm, MSpace.Space.kObject);
                    vert.normal = new Vector3((float)mayaNrm.x, (float)mayaNrm.y, (float)mayaNrm.z);

                    // Texcoords.
                    if( hasUvs && it.hasUVsProperty )
                    {
                        float[] mayaUvs = new float[2];
                        it.getUV(mayaUvs, uvSetNames[0]);
                        vert.texcoord = new Vector2(mayaUvs[0], mayaUvs[1]);
                    }

                    // Append the vertex.
                    mesh.vertices.Add(vert);
                    it.next();
                }

                // Get all index data.
                MIntArray mia1 = new MIntArray();
                MIntArray mia2 = new MIntArray();
                mayaMesh.getTriangleOffsets(mia1, mia2);
                foreach( int idx in mia2 )
                {
                    mesh.indices.Add((uint)idx);
                }
            }
        }
Esempio n. 49
0
        public MFnMesh GetFirstMesh()
        {
               var selected = GetFirstSelectedMesh();

               MFnMesh mesh=null;
                // The reason why there might not be a selection is if some tool isn't closed
                // and prevent the previous selection command from going through
                if (selected != null)
                {
                    if (selected.node.apiTypeStr == "kMesh")
                    {
                        mesh = new MFnMesh(selected);
                          
                    }

                    if (selected.node.apiTypeStr == "kTransform")
                    {
                        MFnTransform trans = new MFnTransform(selected); 
                        mesh = new MFnMesh(trans.child(0)); 
                    }
                }

                return mesh;
        }
Esempio n. 50
0
 public void UpdateMeshMaya(MFnMesh fnMesh, TriMesh triMesh)
 {
     for (int i = 0; i < triMesh.Vertices.Count; i++)
     {
         MPoint pos = new MPoint(triMesh.Vertices[i].Traits.Position.x,
                                 triMesh.Vertices[i].Traits.Position.y,
                                 triMesh.Vertices[i].Traits.Position.z);
         fnMesh.setPoint(i, pos);
     }
 }
Esempio n. 51
0
		//
		// Description
		//
		//     This function takes an input surface of type kMeshData and converts
		//     the geometry into this nodes attributes.
		//     Returns false if nothing is connected.
		//
		public bool computeInputMesh(MPlug plug,
									 MDataBlock datablock,
									 MPointArray vertices,
									 MIntArray counts,
									 MIntArray connects,
									 MVectorArray normals,
									 apiMeshGeomUV uvs)
		{
			// Get the input subdiv
			//
			MDataHandle inputData = datablock.inputValue( inputMesh );
			MObject surf = inputData.asMesh;

			// Check if anything is connected
			//
			MObject thisObj = thisMObject();
			MPlug surfPlug = new MPlug( thisObj, inputMesh );
			if ( !surfPlug.isConnected )
			{
				datablock.setClean( plug );
				return false;
			}

			// Extract the mesh data
			//
			MFnMesh surfFn = new MFnMesh(surf);
			surfFn.getPoints( vertices, MSpace.Space.kObject );

			// Check to see if we have UVs to copy.
			//
			bool hasUVs = surfFn.numUVsProperty > 0;
			surfFn.getUVs( uvs.ucoord, uvs.vcoord );

			for ( int i=0; i<surfFn.numPolygons; i++ )
			{
				MIntArray polyVerts = new MIntArray();
				surfFn.getPolygonVertices( i, polyVerts );
				int pvc = (int)polyVerts.length;
				counts.append( pvc );
				int uvId;
				for ( int v=0; v<pvc; v++ )
				{
					if ( hasUVs )
					{
						surfFn.getPolygonUVid( i, v, out uvId );
						uvs.faceVertexIndex.append( uvId );
					}
					connects.append( polyVerts[v] );
				}
			}

			for ( int n=0; n<(int)vertices.length; n++ )
			{
				MVector normal = new MVector();
				surfFn.getVertexNormal( n, normal );
				normals.append( normal );
			}

			return true;
		}
Esempio n. 52
0
		private void createNodes()
		{
			// Generate the raw data for the requested primitive.
			generatePrimitiveData();

			// 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.
			MFnMesh        meshFn = new MFnMesh();
			MObject        dataObj = meshFn.create(
										num_verts,
										num_faces,
										pa,
										faceCounts,
										faceConnects,
										dataWrapper
									);

			// Use the DAG modifier to create an empty mesh node and its parent
			// transform.
			MObject transform = dagMod.createNode("mesh", MObject.kNullObj);

			// Commit the creation so that the transform and its child will be
			// valid below.
			dagMod.doIt();

			// At the moment we have a transform named something like 'transform1'
			// and a mesh named something like 'polySurfaceShape1'. Let's tidy that
			// up by renaming them as 'pPrimitive#' and 'pPrimitiveShape#', where
			// '#' is a number to ensure uniqueness.
			renameNodes(transform, "pPrimitive");
			// Commit the rename so that assignShadingGroup() can get the new name.
			dagMod.doIt();

			// Assign the mesh to a shading group.
			assignShadingGroup(transform, "initialShadingGroup");

			// Commit the changes.
			dagMod.doIt();

			// Set the mesh node to use the geometry we created for it.
			setMeshData(transform, dataWrapper);
		}
Esempio n. 53
0
        public Material MakeMaterial(MFnMesh fnMesh)
        {
            MaterialGroup matGroup =new MaterialGroup () ;

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

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

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

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

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

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

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

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

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

                        // No specular color

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

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

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

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

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

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

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

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

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

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

            // Default to Blue
            if ( matGroup.Children.Count == 0 )
                 matGroup.Children.Add (new DiffuseMaterial (new SolidColorBrush (Color.FromRgb (0, 0, 255)))) ;
            return (matGroup) ;
        }
Esempio n. 54
0
        public ModelVisual3D MakeVisualModel(MDagPath path)
        {
            var mesh =new MFnMesh (path) ;
            var r =new ModelVisual3D () ;
            r.Content =MakeModel (mesh) ;
            r.Transform =new Transform3DGroup () ;
            Transform3DGroup transformGroup =r.Transform as Transform3DGroup ;

            MTransformationMatrix matrix =new MTransformationMatrix (path.inclusiveMatrix) ;
            //MVector tr =matrix.getTranslation (MSpace.Space.kWorld) ;
            //TranslateTransform3D translation =new TranslateTransform3D (tr.x, tr.y, tr.z) ;
            //transformGroup.Children.Add (translation) ;

            //double x =0, y =0, z =0, w =0 ;
            //matrix.getRotationQuaternion (ref x, ref y, ref z, ref w, MSpace.Space.kWorld) ;
            //QuaternionRotation3D rotation =new QuaternionRotation3D (new Quaternion (x, y, z, w)) ;
            //transformGroup.Children.Add (new RotateTransform3D (rotation)) ;

            //double [] scales =new double [3] ;
            //matrix.getScale (scales, MSpace.Space.kWorld) ;
            //ScaleTransform3D scale =new ScaleTransform3D (scales [0], scales [1], scales [2]) ;
            //transformGroup.Children.Add (scale) ;

            MMatrix mat =matrix.asMatrixProperty ;
            Matrix3D matrix3d =new Matrix3D (mat [0, 0], mat [0, 1], mat [0, 2], mat [0, 3],
                                             mat [1, 0], mat [1, 1], mat [1, 2], mat [1, 3],
                                             mat [2, 0], mat [2, 1], mat [2, 2], mat [2, 3],
                                             mat [3, 0], mat [3, 1], mat [3, 2], mat [3, 3]) ;
            MatrixTransform3D matrixTransform = new MatrixTransform3D (matrix3d) ;
            transformGroup.Children.Add (matrixTransform) ;

            return (r) ;
        }
Esempio n. 55
0
       public TriMesh ConvertTriMesh(MFnMesh mesh)
       {
            if(mesh==null)
            {
                MGlobal.displayInfo("Mesh is null \n");
            }

           TriMesh trimesh = new TriMesh();

           MIntArray indices = new MIntArray();
           MIntArray triangleCounts = new MIntArray();
           MPointArray points = new MPointArray();

           mesh.getTriangles(triangleCounts, indices);
           mesh.getPoints(points);

           // Get the triangle indices 
        
           for (int i = 0; i < (int)points.length; ++i)
           {
               MPoint pt = points[i];
               VertexTraits trait = new VertexTraits(pt.x, pt.y, pt.z);
               trimesh.Vertices.Add(trait);
           }
           
           
           MGlobal.displayInfo( indices.Count.ToString() +"\n");
           int j=0;
           while(j<indices.Count)
           {
               int a = indices[j];
               j++;
               int b = indices[j];
               j++;
               int c = indices[j];
               j++;
               trimesh.Faces.AddTriangles(trimesh.Vertices[a], trimesh.Vertices[b], trimesh.Vertices[c]);
                
           } 
           return trimesh;
       }
Esempio n. 56
0
        unsafe public override void getTweakedUVs(MObject meshObj, MIntArray uvList, MFloatArray uPos, MFloatArray vPos)
        {
            int i = 0;
            MFloatArray uArray = new MFloatArray();
            MFloatArray vArray = new MFloatArray();
            MFnMesh mesh = new MFnMesh(meshObj);
            mesh.getUVs(uArray, vArray);

            uint nbUvShells = 0;
            MIntArray uvShellIds = new MIntArray();

            if ((!flipGlobal) || extendToShell)
                // First, extract the UV shells.
                mesh.getUvShellsIds(uvShellIds, ref nbUvShells);

            if (extendToShell)
            {
                bool[] selected = new bool[nbUvShells];
                for (i = 0; i < nbUvShells; i++)
                {
                    selected[i] = false;
                }

                for (i = 0; i < nbUvShells; i++)
                {
                    int index = uvList[i];
                    index = uvShellIds[index];
                    selected[index] = true;
                }

                uint numUvs = (uint)mesh.numUVsProperty;
                uint numSelUvs = 0;

                // Preallocate a buffer, large enough to hold all Ids. This
                // prevents multiple reallocation from happening when growing
                // the array.
                uvList.length = numUvs;

                for (i = 0; i < numUvs; i++)
                {
                    int index = uvShellIds[i];
                    if (selected[index])
                    {
                        uvList.set((int)i, numSelUvs);
                        numSelUvs++;
                    }
                }

                // clamp the array to the proper size.
                uvList.length = numSelUvs;
            }

            int nbUvShellsInt = (int)nbUvShells;
            // For global flips, just pretend there is only one shell
            if (flipGlobal)
                nbUvShellsInt = 1;

            float[] minMax = new float[nbUvShellsInt * 4];

            for (i = 0; i < nbUvShellsInt; i++)
            {
                minMax[4 * i + 0] = 1e30F;				// Min U
                minMax[4 * i + 1] = 1e30F;				// Min V
                minMax[4 * i + 2] = -1e30F;				// Max U
                minMax[4 * i + 3] = -1e30F;				// Max V
            }

            // Get the bounding box of the UVs, for each shell if flipGlobal
            // is true, or for the whole selection if false.
            for (i = 0; i < uvList.length; i++)
            {
                int indx = uvList[i];
                int shellId = 0;

                if (!flipGlobal)
                {
                    shellId = uvShellIds[indx];
                }

                float value = uArray[indx];
                
                if (value < minMax[4 * shellId + 0])
                    minMax[4 * shellId + 0] = value;

                value = vArray[indx];
                if (value < minMax[4 * shellId + 1])
                    minMax[4 * shellId + 1] = value;

                value = uArray[indx];
                if (value > minMax[4 * shellId + 2])
                    minMax[4 * shellId + 2] = value;

                value = vArray[indx];
                if (value > minMax[4 * shellId + 3])
                    minMax[4 * shellId + 3] = value;
            }

            // Adjust the size of the output arrays
            uPos.length = uvList.length;
            vPos.length = uvList.length;

            for (i = 0; i < uvList.length; i++)
            {
                int shellId = 0;

                int indx = uvList[i];

                if (!flipGlobal)
                    shellId = uvShellIds[indx];

                // Flip U or V along the bounding box center.
                if (horizontal)
                {
                    float value = uArray[indx];
                    value = minMax[4 * shellId + 0] + minMax[4 * shellId + 2] - value;

                    uPos.set(value, (uint)i);
                    value = vArray[indx];
                    vPos.set(value, (uint)i);
                }
                else
                {
                    float value = uArray[indx];
                    uPos.set(value, (uint)i);

                    value = vArray[indx];
                    value = minMax[4 * shellId + 1] + minMax[4 * shellId + 3] - value;
                    vPos.set(value, (uint)i);
                }
            }
            return;
        }