Example #1
0
        /// <summary>
        /// Creates a new mesh and fills it with the data of a previously loaded mesh.
        /// </summary>
        /// <param name="positionElement">The semantic name for the position data. </param>
        /// <param name="elements">Array of <see cref="InputElement"/> structures, describing the vertex format for the returned mesh. See <see cref="SharpDX.Direct3D10.InputElement"/>. </param>
        /// <param name="flags">Creation flags to be applied to the new mesh. See <see cref="MeshFlags"/>.</param>
        /// <returns>returns the Mesh cloned. </returns>
        /// <unmanaged>HRESULT ID3DX10Mesh::CloneMesh([None] int Flags,[None] const char* pPosSemantic,[In, Buffer] const D3D10_INPUT_ELEMENT_DESC* pDesc,[None] int DeclCount,[None] ID3DX10Mesh** ppCloneMesh)</unmanaged>
        public Mesh Clone(InputElement[] elements, string positionElement, MeshFlags flags)
        {
            Mesh temp;

            CloneMesh((int)flags, positionElement, elements, elements.Length, out temp);
            return(temp);
        }
    /// <summary>
    /// Creates a new mesh
    /// </summary>
    /// <param name="device">The device used to create the mesh</param>
    /// <param name="filename">the file to load</param>
    public void Create(Device device, string filename)
    {
        worldPosition = new WorldPosition();

        GraphicsStream adjacencyBuffer;

        ExtendedMaterial[] Mat;

        this.device = device;
        if (device != null)
        {
            device.DeviceLost  += new System.EventHandler(this.InvalidateDeviceObjects);
            device.Disposing   += new System.EventHandler(this.InvalidateDeviceObjects);
            device.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }
        filename = MediaUtilities.FindFile(filename);
        // Load the mesh
        systemMemoryMesh = Mesh.FromFile(filename, MeshFlags.SystemMemory, device, out adjacencyBuffer, out Mat);

        Mesh   tempMesh = null;
        string errorString;

        tempMesh = Mesh.Clean(CleanType.Optimization, systemMemoryMesh, adjacencyBuffer, adjacencyBuffer, out errorString);
        if (tempMesh != systemMemoryMesh)
        {
            systemMemoryMesh.Dispose();
            systemMemoryMesh = tempMesh;
        }

        // Optimize the mesh for performance
        MeshFlags flags = MeshFlags.OptimizeCompact | MeshFlags.OptimizeAttributeSort | MeshFlags.OptimizeVertexCache;

        systemMemoryMesh.OptimizeInPlace(flags, adjacencyBuffer);
        adjacencyBuffer.Close();
        adjacencyBuffer = null;
        // Setup bounding volumes
        VertexBuffer   vb         = systemMemoryMesh.VertexBuffer;
        GraphicsStream vertexData = vb.Lock(0, 0, LockFlags.ReadOnly);

        boundingSphere.Radius = Geometry.ComputeBoundingSphere(vertexData, systemMemoryMesh.NumberVertices, systemMemoryMesh.VertexFormat, out boundingSphere.CenterPoint);
        vb.Unlock();
        vb.Dispose();

        textures  = new Texture[Mat.Length];
        materials = new Direct3D.Material[Mat.Length];

        for (int i = 0; i < Mat.Length; i++)
        {
            materials[i] = Mat[i].Material3D;
            // Set the ambient color for the material (D3DX does not do this)
            materials[i].Ambient = materials[i].Diffuse;

            if (Mat[i].TextureFilename != null)
            {
                // Create the texture
                textures[i] = TextureLoader.FromFile(device, MediaUtilities.FindFile(Mat[i].TextureFilename));
            }
        }
        RestoreDeviceObjects(device, null);
    }
Example #3
0
        public uint Add(IntPtr scenePtr, MeshFlags flags)
        {
            var meshID = RTC.NewTriangleMesh(scenePtr, flags, triangleCount, vertexCount, 1);

            RTC.CheckLastError();
            return(meshID);
        }
Example #4
0
        /// <summary>
        ///		Initilizes a new mesh from a file.
        /// </summary>
        /// <param name="path">Memory location (or url) of mesh file to load.</param>
        public Mesh(object path, MeshFlags flags)
        {
            if ((path is VertexMap) == false)
            {
                if (path is string)
                {
                    _url = (string)path;
                }
                _vertexMap = VertexMapFactory.LoadVertexMap(path);
            }
            else
            {
                _vertexMap = (path as VertexMap).Copy();
            }

            if (_vertexMap == null)
            {
                return;
            }

            _flags      = flags;
            _driverMesh = GraphicsManager.CreateDriverMesh(_vertexMap);

            // Are we dynamic? If not we don't need the full vertexmaps data so lets destroy it and
            // free up a bit of memory.
            //if ((_flags & MeshFlags.Dynamic) == 0 && _vertexMap != null)
            //{
            //    _vertexMap.Data = null;
            //}
        }
Example #5
0
        /// <summary>Generate a mesh that can be tesselated.</summary>
        private void GenerateEnhancedMesh(Device device, int newNumberSegs)
        {
            Mesh meshEnhancedSysMem = null;
            Mesh meshTemp           = null;

            if (systemMemoryMesh == null)
            {
                return;
            }

            // if using hw, just copy the mesh
            if (isUsingHardwarePatches)
            {
                meshTemp = systemMemoryMesh.Clone(MeshFlags.WriteOnly | MeshFlags.NPatches |
                                                  (systemMemoryMesh.Options.Value & MeshFlags.Use32Bit),
                                                  systemMemoryMesh.VertexFormat, device);
            }
            else  // tesselate the mesh in sw
            {
                try
                {
                    // Create an enhanced version of the mesh, will be in sysmem since source is
                    meshEnhancedSysMem = Mesh.TessellateNPatches(systemMemoryMesh, adjacencyBuffer,
                                                                 newNumberSegs, false);
                }
                catch
                {
                    // If the tessellate failed, there might have been more triangles or vertices
                    // than can fit into a 16bit mesh, so try cloning to 32bit before tessellation
                    using (meshTemp = systemMemoryMesh.Clone(MeshFlags.SystemMemory | MeshFlags.Use32Bit, systemMemoryMesh.VertexFormat, device))
                    {
                        meshEnhancedSysMem = Mesh.TessellateNPatches(meshTemp, adjacencyBuffer, newNumberSegs, false);
                    }
                }

                using (meshEnhancedSysMem)
                {
                    // Make a video memory version of the mesh
                    // Only set WriteOnly if it doesn't use 32bit indices, because those
                    // often need to be emulated, which means that D3DX needs read-access.
                    MeshFlags meshEnhancedFlags = meshEnhancedSysMem.Options.Value & MeshFlags.Use32Bit;
                    if ((meshEnhancedFlags & MeshFlags.Use32Bit) == 0)
                    {
                        meshEnhancedFlags |= MeshFlags.WriteOnly;
                    }

                    meshTemp = meshEnhancedSysMem.Clone(meshEnhancedFlags, systemMemoryMesh.VertexFormat, device);
                }
            }

            // Cleanup enhanced mesh if already exists
            if (vidMemEnhancedMesh != null)
            {
                vidMemEnhancedMesh.Dispose();
            }

            vidMemEnhancedMesh = meshTemp;
            numberSegments     = newNumberSegs;
        }
Example #6
0
 public MeshData(MeshFlags flags = MeshFlags.Base)
 {
     this.vertices = new List <Vector3>();
     this.indices  = new List <int>();
     this.colors   = new List <Color>();
     this.UVs      = new List <Vector2>();
     this._flags   = flags;
 }
Example #7
0
        public override object Create()
        {
            string    fileName  = null;
            MeshFlags meshFlags = 0;
            Mesh      mesh      = null;

            ExtendedMaterial[]          mtrl               = null;
            Material[]                  materials          = null;
            Texture[]                   textures           = null;
            Dictionary <string, string> customTextureNames = null;
            string texturesPath = "";
            string name         = null;

            HandleActionMap(new Dictionary <string, Action <object> >
            {
                { "File", (object o) => { fileName = (string)o; } },
                { "MeshFlags", (object o) => { meshFlags = ParseMeshFlags((string)o); } },
                { "TexturesPath", (object o) => { texturesPath = (string)o + @"\"; } },
                { "Name", (object o) => { name = (string)o; } },
                { "CustomTextures", (object o) => { customTextureNames = ParseTextures(o); } }
            });
            Device device = SceneContext.Shared.Device;



            SceneContext.MeshData cachedMeshData = null;
            try
            {
                cachedMeshData = SceneContext.Shared.Meshes[fileName];
            } catch (Exception e)
            {
                //TODO: log
            }
            string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

            if (cachedMeshData == null)
            {
                mesh = Mesh.FromFile(fileName, meshFlags, device, out mtrl);
                LoadDecorations(device, mtrl, out materials, out textures, texturesPath, customTextureNames);
                SceneContext.Shared.Meshes[fileName] = new SceneContext.MeshData(mesh, mtrl);
            }
            else
            {
                mesh = cachedMeshData.mesh;
                mtrl = cachedMeshData.materials;
                LoadDecorations(device, mtrl, out materials, out textures, texturesPath, customTextureNames);
            }


            var skin = new Skin(mesh, materials, textures);

            if (name != null)
            {
                SceneContext.Shared.Skins[name] = skin;
            }

            return(skin);
        }
Example #8
0
 void FlaggedGUI(GUIDelegate gui, MeshFlags affectsMesh = MeshFlags.None, bool affectsShader = false)
 {
     GUI.changed = false;
     gui();
     if (GUI.changed)
     {
         MarkAsDirty(serializedObject, affectsMesh, affectsShader);
     }
 }
Example #9
0
            public StripifyArguments(OpsParsedStatement statement)
            {
                OpsParsedArgument splits = statement.FindArgument("splits");

                if (splits != null && int.Parse(splits.Value) == 0)
                {
                    meshFlags |= MeshFlags.OptimizeDoNotSplit;
                }
            }
Example #10
0
 void FlaggedLayoutPropertyField(SerializedProperty property, GUIContent label, MeshFlags affectsMesh = MeshFlags.None, bool affectsShader = false, bool disabled = false)
 {
     EditorGUI.BeginDisabledGroup(disabled);
     GUI.changed = false;
     EditorGUILayout.PropertyField(property, label);
     if (GUI.changed)
     {
         MarkAsDirty(property.serializedObject, affectsMesh, affectsShader);
     }
     EditorGUI.EndDisabledGroup();
 }
Example #11
0
        private MeshFlags ParseMeshFlags(string flagsString)
        {
            MeshFlags flags = 0;

            string[] flagStrings = flagsString.Split(',');
            foreach (string flagString in flagStrings)
            {
                MeshFlags flag = ParseMeshFlag(flagString.Trim());
                flags |= flag;
            }
            return(flags);
        }
Example #12
0
 // Most of our meshes are planes, so we know a plane
 // is 4 vertices and 6 triangles, most of the time we will
 // know the capacity of our lists.
 public MeshData(int planeCount, MeshFlags flags = MeshFlags.Base)
 {
     this.vertices = new List <Vector3>(planeCount * 4);
     this.indices  = new List <int>(planeCount * 6);
     this.colors   = new List <Color>(
         (flags & MeshFlags.Color) == MeshFlags.Color ? planeCount * 4 : 0
         );
     this.UVs = new List <Vector2>(
         (flags & MeshFlags.UV) == MeshFlags.UV ? planeCount * 4 : 0
         );
     this._flags = flags;
 }
Example #13
0
        public static MeshFlags Update(MeshFlags flag, bool condition, MeshFlags conditionFlag)
        {
            if (condition)
            {
                flag |= conditionFlag;
            }
            else
            {
                flag &= ~conditionFlag;
            }

            return(flag);
        }
Example #14
0
            /// <summary>
            /// Vztvoreni skinned meshe
            /// </summary>
            /// <param name="mesh">Container s meshem</param>
            /// <param name="adjacency">adjacency</param>
            static void GenerateSkinnedMesh(AnimationMeshContainer mesh, GraphicsStream adjacency)
            {
                if (mesh.SkinInformation == null)
                {
                    throw new ArgumentException();  // There is nothing to generate
                }
                MeshFlags flags = MeshFlags.OptimizeVertexCache;

                flags |= MeshFlags.Managed;


                int numMaxFaceInfl;

                using (IndexBuffer ib = mesh.MeshData.Mesh.IndexBuffer)
                {
                    numMaxFaceInfl = mesh.SkinInformation.GetMaxFaceInfluences(ib,
                                                                               mesh.MeshData.Mesh.NumberFaces);
                }
                // 12 entry palette guarantees that any triangle (4 independent
                // influences per vertex of a tri) can be handled
                numMaxFaceInfl = (int)Math.Min(numMaxFaceInfl, 12);


                mesh.NumberPaletteEntries = 4;

                int influences = 0;

                BoneCombination[] bones = null;

                // Use ConvertToBlendedMesh to generate a drawable mesh
                MeshData data = mesh.MeshData;

                data.Mesh = mesh.SkinInformation.ConvertToIndexedBlendedMesh(data.Mesh, flags, mesh.GetAdjacencyStream(), mesh.NumberPaletteEntries, out influences, out bones);



                int use32Bit = (int)(data.Mesh.Options.Value & MeshFlags.Use32Bit);


                mesh.NumberInfluences = influences;
                mesh.SetBones(bones);

                // Get the number of attributes
                mesh.NumberAttributes = bones.Length;

                mesh.MeshData = data;
            }
Example #15
0
        /// Get the current mesh for the graphic instance (or create a new one)
        public MeshData GetMesh(int graphicInstance, bool useSize = true, MeshFlags flags = MeshFlags.Base)
        {
            if (this.meshes.ContainsKey(graphicInstance))
            {
                return(this.meshes[graphicInstance]);
            }

            if (useSize)
            {
                this.meshes.Add(graphicInstance, new MeshData(this.bucket.rect.area, flags));
            }
            else
            {
                this.meshes.Add(graphicInstance, new MeshData(flags));
            }

            return(this.meshes[graphicInstance]);
        }
Example #16
0
 void MarkAsDirty(SerializedObject obj, MeshFlags mesh, bool shader)
 {
     for (int i = 0; i < obj.targetObjects.Length; i++)
     {
         PAParticleField field = obj.targetObjects[i] as PAParticleField;
         if (field)
         {
             if (mesh != MeshFlags.None)
             {
                 field.meshIsDirtyMask = mesh;
             }
             if (shader)
             {
                 field.shaderIsDirty = true;
             }
         }
     }
 }
Example #17
0
            private void Parse(Stream s)
            {
                BinaryReader br           = new BinaryReader(s);
                long         expectedSize = br.ReadUInt32();
                long         start        = s.Position;

                mName              = br.ReadUInt32();
                mMaterialIndex     = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, s);
                mVertexFormatIndex = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, s);
                mVertexBufferIndex = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, s);
                mIndexBufferIndex  = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, s);
                uint val = br.ReadUInt32();

                mPrimitiveType       = (ModelPrimitiveType)(val & 0x000000FF);
                mFlags               = (MeshFlags)(val >> 8);
                mStreamOffset        = br.ReadUInt32();
                mStartVertex         = br.ReadInt32();
                mStartIndex          = br.ReadInt32();
                mMinVertexIndex      = br.ReadInt32();
                mVertexCount         = br.ReadInt32();
                mPrimitiveCount      = br.ReadInt32();
                mBounds              = new BoundingBox(0, handler, s);
                mSkinControllerIndex = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, s);
                mJointReferences     = new UIntList(handler, s);
                mScaleOffsetIndex    = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, s);
                mGeometryStates      = new GeometryStateList(handler, s);
                if (mOwner.Version > 0x00000201)
                {
                    mParentName  = br.ReadUInt32();
                    mMirrorPlane = new Vector4(0, handler, s);
                }
                if (mOwner.Version > 0x00000203)
                {
                    mUnknown1 = br.ReadUInt32();
                }
                long actualSize = s.Position - start;

                if (checking && actualSize != expectedSize)
                {
                    throw new Exception(String.Format("Expected end at {0}, actual end was {1}", expectedSize,
                                                      actualSize));
                }
            }
Example #18
0
            public Mesh(int apiVersion, EventHandler handler, MLOD owner,
                        uint name,
                        GenericRCOLResource.ChunkReference materialIndex, GenericRCOLResource.ChunkReference vertexFormatIndex,
                        GenericRCOLResource.ChunkReference vertexBufferIndex, GenericRCOLResource.ChunkReference indexBufferIndex,
                        ModelPrimitiveType primitiveType, MeshFlags flags,
                        uint streamOffset, int startVertex, int startIndex, int minVertexIndex, int vertexCount, int primitiveCount,
                        BoundingBox bounds, GenericRCOLResource.ChunkReference skinControllerIndex,
                        UIntList jointReferences, GeometryStateList geometryStates, GenericRCOLResource.ChunkReference scaleOffsetIndex,
                        uint parentName, Vector4 mirrorPlane, uint unknown1
                        )
                : base(apiVersion, handler)
            {
                mOwner = owner;

                mName                = name;
                mMaterialIndex       = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, materialIndex);
                mVertexFormatIndex   = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, vertexFormatIndex);
                mVertexBufferIndex   = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, vertexBufferIndex);
                mIndexBufferIndex    = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, indexBufferIndex);
                mPrimitiveType       = primitiveType;
                mFlags               = flags;
                mStreamOffset        = streamOffset;
                mStartVertex         = startVertex;
                mStartIndex          = startIndex;
                mMinVertexIndex      = minVertexIndex;
                mVertexCount         = vertexCount;
                mPrimitiveCount      = primitiveCount;
                mBounds              = new BoundingBox(requestedApiVersion, handler, bounds);
                mSkinControllerIndex = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, skinControllerIndex);
                mJointReferences     = jointReferences == null ? null : new UIntList(handler, jointReferences);
                mGeometryStates      = geometryStates == null ? null : new GeometryStateList(handler, geometryStates);
                mScaleOffsetIndex    = new GenericRCOLResource.ChunkReference(requestedApiVersion, handler, scaleOffsetIndex);
                if (mOwner.Version > 0x00000201)
                {
                    mParentName  = parentName;
                    mMirrorPlane = new Vector4(requestedApiVersion, handler, mirrorPlane);
                }
                if (mOwner.Version > 0x00000203)
                {
                    mUnknown1 = unknown1;
                }
            }
Example #19
0
        private ImmutableArray <Mesh> LoadMeshes(BinaryReader reader, int count)
        {
            Mesh[] meshes = new Mesh[count];
            for (int i = 0; i < count; ++i)
            {
                long offset = reader.BaseStream.Position;

                int       stripGroupCount  = reader.ReadInt32();
                long      stripGroupOffset = offset + reader.ReadInt32();
                MeshFlags flags            = (MeshFlags)reader.ReadByte();

                long save = reader.BaseStream.Position;
                reader.BaseStream.Position = stripGroupOffset;
                ImmutableArray <StripGroup> stripGroups = LoadStripGroups(reader, stripGroupCount);
                reader.BaseStream.Position = save;

                meshes[i] = new Mesh(flags, stripGroups);
            }
            return(new ImmutableArray <Mesh>(meshes));
        }
Example #20
0
        /// <summary>
        ///		Loads an mesh as renderable data.
        /// </summary>
        /// <param name="path">Memory location (or url) of mesh file to load.</param>
        /// <param name="cache">If set to true this image is added to the resource cache to save loading
        ///                     time when this image is requested again.</param>
        /// <param name="flags">Describes how this image should be loaded, rendered and stored.</param>
        /// <returns>A new instance of the Image class if the image file can be loaded.</returns>
        public static Mesh LoadMesh(object path, MeshFlags flags, bool cache)
        {
            if (ResourceManager.ResourceIsCached(path.ToString()) == true)
            {
                DebugLogger.WriteLog("Loading mesh " + path.ToString() + " from cache.");
                return((Mesh)ResourceManager.RetrieveResource(path.ToString()));
            }

            DebugLogger.WriteLog("Loading mesh from " + path.ToString() + ".");
            Mesh mesh = new Mesh(path, flags);

            if (cache == true)
            {
                if ((flags & MeshFlags.Dynamic) != 0)
                {
                    throw new Exception("Dynamic meshs cannot be cached.");
                }
                ResourceManager.CacheResource(path.ToString(), mesh);
            }
            return(mesh);
        }
Example #21
0
        /// <summary>
        ///		Initilizes a new mesh from a file.
        /// </summary>
        /// <param name="path">Memory location (or url) of mesh file to load.</param>
        public Mesh(object path, MeshFlags flags)
        {
            if ((path is VertexMap) == false)
            {
                if (path is string) _url = (string)path;
                _vertexMap = VertexMapFactory.LoadVertexMap(path);
            }
            else
                _vertexMap = (path as VertexMap).Copy();

            if (_vertexMap == null)
                return;

            _flags = flags;
            _driverMesh = GraphicsManager.CreateDriverMesh(_vertexMap);

            // Are we dynamic? If not we don't need the full vertexmaps data so lets destroy it and
            // free up a bit of memory.
            //if ((_flags & MeshFlags.Dynamic) == 0 && _vertexMap != null)
            //{
            //    _vertexMap.Data = null;
            //}
        }
Example #22
0
 public static Mesh LoadMesh(object path, MeshFlags flags)
 {
     return LoadMesh(path, flags, true);
 }
Example #23
0
        private static void CreateGeometry(SceneFlags sceneFlags, TraversalFlags traversalFlags, MeshFlags meshFlags, TriangleMesh sphere, int numMeshes)
        {
            using (var scene = new Scene<Sphere>(sceneFlags, traversalFlags))
            {
                for (var t = 0; t < numMeshes; ++t)
                {
                    scene.Add(new Sphere(sceneFlags, traversalFlags, sphere, meshFlags));

                    for (int v = 0; v < sphere.Vertices.Count; ++v)
                        sphere.Vertices[v] = (Vector)sphere.Vertices[v] + new Vector(1, 1, 1);
                }

                scene.Commit();
            }
        }
Example #24
0
 void FlaggedPropertyField(Rect propRect, SerializedProperty property, GUIContent label, MeshFlags affectsMesh = MeshFlags.None, bool affectsShader = false)
 {
     GUI.changed = false;
     EditorGUI.PropertyField(propRect, property, label);
     if (GUI.changed)
     {
         MarkAsDirty(property.serializedObject, affectsMesh, affectsShader);
     }
 }
Example #25
0
File: Mesh.cs Project: Nezz/SharpDX
 /// <summary>	
 /// Creates a new mesh and fills it with the data of a previously loaded mesh.	
 /// </summary>	
 /// <param name="positionElement">The semantic name for the position data. </param>
 /// <param name="elements">Array of <see cref="InputElement"/> structures, describing the vertex format for the returned mesh. See <see cref="SharpDX.Direct3D10.InputElement"/>. </param>
 /// <param name="flags">Creation flags to be applied to the new mesh. See <see cref="MeshFlags"/>.</param>
 /// <returns>returns the Mesh cloned. </returns>
 /// <unmanaged>HRESULT ID3DX10Mesh::CloneMesh([None] int Flags,[None] const char* pPosSemantic,[In, Buffer] const D3D10_INPUT_ELEMENT_DESC* pDesc,[None] int DeclCount,[None] ID3DX10Mesh** ppCloneMesh)</unmanaged>
 public Mesh Clone(InputElement[] elements, string positionElement, MeshFlags flags)
 {
     Mesh temp;
     CloneMesh((int) flags, positionElement, elements, elements.Length, out temp);
     return temp;
 }
Example #26
0
 /// <summary>
 ///		Initializes a blank mesh.
 /// </summary>
 public Mesh(MeshFlags flags)
 {
     _flags = flags;
 }
Example #27
0
 public uint Add(IntPtr scenePtr, MeshFlags flags)
 {
     var meshID = RTC.NewTriangleMesh(scenePtr, flags, triangleCount, vertexCount, 1);
     RTC.CheckLastError();
     return meshID;
 }
Example #28
0
 /// <summary>
 ///		Creates a blank mesh.
 /// </summary>
 /// <param name="flags">Describes how this image mesh be loaded, rendered and stored.</param>
 /// <returns>A new mesh instance.</returns>
 public static Mesh CreateMesh(MeshFlags flags)
 {
     return new Mesh(flags);
 }
Example #29
0
 public PatchMesh Clone(MeshFlags options, GraphicsStream decl)
 {
     throw new NotImplementedException();
 }
Example #30
0
 public static PatchMesh FromX(XFileData xofObjMesh, MeshFlags options, Device device)
 {
     throw new NotImplementedException();
 }
Example #31
0
 public Sphere(SceneFlags sceneFlags, TraversalFlags traversalFlags, IMesh mesh, MeshFlags meshFlags = MeshFlags.Static)
 {
     geometry = new Geometry(sceneFlags, traversalFlags);
     geometry.Add(mesh, meshFlags);
 }
Example #32
0
 public Mesh Clone(MeshFlags options, VertexElement[] declaration, Device device)
 {
     throw new NotImplementedException();
 }
Example #33
0
 public Sphere(SceneFlags sceneFlags, TraversalFlags traversalFlags, int numPhi, MeshFlags meshFlags = MeshFlags.Static)
 {
     geometry = new Geometry(sceneFlags, traversalFlags);
     geometry.Add(GenerateSphere(numPhi), meshFlags);
 }
Example #34
0
        /// <summary>
        ///		Loads an mesh as renderable data.
        /// </summary>
        /// <param name="path">Memory location (or url) of mesh file to load.</param>
        /// <param name="cache">If set to true this image is added to the resource cache to save loading
        ///                     time when this image is requested again.</param>
        /// <param name="flags">Describes how this image should be loaded, rendered and stored.</param>
        /// <returns>A new instance of the Image class if the image file can be loaded.</returns>
        public static Mesh LoadMesh(object path, MeshFlags flags, bool cache)
        {
            if (ResourceManager.ResourceIsCached(path.ToString()) == true)
            {
                DebugLogger.WriteLog("Loading mesh " + path.ToString() + " from cache.");
                return (Mesh)ResourceManager.RetrieveResource(path.ToString());
            }

            DebugLogger.WriteLog("Loading mesh from " + path.ToString() + ".");
            Mesh mesh = new Mesh(path, flags);
            if (cache == true)
            {
                if ((flags & MeshFlags.Dynamic) != 0)
                    throw new Exception("Dynamic meshs cannot be cached.");
                ResourceManager.CacheResource(path.ToString(), mesh);
            }
            return mesh;
        }
Example #35
0
File: Vtx.cs Project: Frassle/Ibasa
 internal Mesh(MeshFlags flags, ImmutableArray<StripGroup> stripGroups)
 {
     Flags = flags;
     StripGroups = stripGroups;
 }
Example #36
0
        /// <summary>
        /// Adds a mesh to the geometry.
        /// </summary>
        public void Add(IMesh mesh, MeshFlags flags = MeshFlags.Static)
        {
            var meshID = mesh.Add(scenePtr, flags);

            meshes.Add(meshID, mesh);
        }
Example #37
0
            public OptimizeArguments(OpsParsedStatement statement)
            {
                OpsParsedArgument splits = statement.FindArgument("splits");
                OpsParsedArgument nocache = statement.FindArgument("nocache");
                OpsParsedArgument weld = statement.FindArgument("weld");
                OpsParsedArgument e = statement.FindArgument("e");
                OpsParsedArgument P = statement.FindArgument("P");
                OpsParsedArgument W = statement.FindArgument("W");
                OpsParsedArgument N = statement.FindArgument("N");
                OpsParsedArgument T = statement.FindArgument("T");
                OpsParsedArgument B = statement.FindArgument("B");
                OpsParsedArgument UV = statement.FindArgument("UV");
                OpsParsedArgument D = statement.FindArgument("D");
                OpsParsedArgument S = statement.FindArgument("S");
                OpsParsedArgument PS = statement.FindArgument("PS");
                OpsParsedArgument F = statement.FindArgument("F");


                if( splits != null && int.Parse(splits.Value) == 0)
                    meshFlags |= MeshFlags.OptimizeDoNotSplit;

                if( nocache != null && int.Parse(nocache.Value) == 0)
                    meshFlags |= MeshFlags.OptimizeVertexCache;

                if( weld != null)
                {
                    if( 0 == String.Compare( weld.Value, "none", true) )
                    {
                        weldType = WeldType.None;
                    }
                    else if( 0 == String.Compare( weld.Value, "all", true) )
                    {
                        weldType = WeldType.All;
                        epsilonFlags |= WeldEpsilonsFlags.WeldAll;
                    }
                }


                if(weldType == WeldType.Epsilon)
                {
                    float delta = 1.0e-6f;

                    if(e != null)
                        delta = float.Parse( e.Value );

                    epsilons.Binormal=delta;
                    epsilons.BlendWeights=delta;
                    epsilons.Diffuse=delta;
                    epsilons.Normal=delta;
                    epsilons.PointSize=delta;
                    epsilons.Position=delta;
                    epsilons.Specular=delta;
                    epsilons.Tangent=delta;
                    epsilons.TessellateFactor=delta;

                    if(P != null)
                        epsilons.Position = float.Parse( P.Value );

                    if(W != null)
                        epsilons.BlendWeights = float.Parse( W.Value );

                    if(N != null)
                        epsilons.Normal = float.Parse( N.Value );

                    if(T != null)
                        epsilons.Tangent = float.Parse( T.Value );

                    if(B != null)
                        epsilons.Binormal = float.Parse( B.Value );

                    float uvDelta = (UV == null) ? delta : float.Parse( UV.Value );
                    float[] uvDeltaArray = epsilons.TextureCoordinate;
                    for( int i = 0; i < uvDeltaArray.Length; i++)
                        uvDeltaArray[i] = uvDelta;
                    epsilons.TextureCoordinate = uvDeltaArray;

                    if(D != null)
                        epsilons.Diffuse = float.Parse( D.Value );

                    if(S != null)
                        epsilons.Specular = float.Parse( S.Value );

                    if(PS != null)
                        epsilons.PointSize = float.Parse( PS.Value );

                    if(F != null)
                        epsilons.TessellateFactor = float.Parse( F.Value );
                }

            
            }
Example #38
0
        private static void CreateGeometry(Device device, SceneFlags sceneFlags, TraversalFlags traversalFlags, MeshFlags meshFlags, TriangleMesh sphere, int numMeshes)
        {
            using (var scene = new Scene <Sphere>(device, sceneFlags, traversalFlags))
            {
                for (var t = 0; t < numMeshes; ++t)
                {
                    scene.Add(new Sphere(device, sceneFlags, traversalFlags, sphere, meshFlags));

                    for (int v = 0; v < sphere.Vertices.Count; ++v)
                    {
                        sphere.Vertices[v] = (Vector)sphere.Vertices[v] + new Vector(1, 1, 1);
                    }
                }

                scene.Commit();
            }
        }
Example #39
0
File: Mesh.cs Project: Nezz/SharpDX
 /// <summary>	
 /// Creates a mesh object using a declarator.	
 /// </summary>	
 /// <param name="device">Pointer to an <see cref="SharpDX.Direct3D10.Device"/>, the device object to be associated with the mesh. </param>
 /// <param name="elements">Array of <see cref="SharpDX.Direct3D10.InputElement"/> elements, describing the vertex format for the returned mesh. This parameter must map directly to a flexible vertex format (FVF). </param>
 /// <param name="positionElement">Semantic that identifies which part of the vertex declaration contains position information. </param>
 /// <param name="vertexCount">Number of vertices for the mesh. This parameter must be greater than 0. </param>
 /// <param name="faceCount">Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the maximum DWORD (typically 65534), because the last index is reserved. </param>
 /// <param name="flags">Combination of one or more flags from the <see cref="MeshFlags"/>, specifying options for the mesh.  </param>
 /// <unmanaged>HRESULT D3DX10CreateMesh([None] ID3D10Device* pDevice,[In, Buffer] const D3D10_INPUT_ELEMENT_DESC* pDeclaration,[None] int DeclCount,[None] const char* pPositionSemantic,[None] int VertexCount,[None] int FaceCount,[None] int Options,[None] ID3DX10Mesh** ppMesh)</unmanaged>
 public Mesh(Device device, InputElement[] elements, string positionElement, int vertexCount, int faceCount, MeshFlags flags)
 {
     D3DX10.CreateMesh(device, elements, elements.Length, positionElement, vertexCount, faceCount, (int) flags, this);
 }
Example #40
0
 public Mesh Clone(MeshFlags options, GraphicsStream declaration, Device device)
 {
     throw new NotImplementedException();
 }
Example #41
0
 public StripifyArguments(OpsParsedStatement statement)
 {
     OpsParsedArgument splits = statement.FindArgument("splits");
     if( splits != null && int.Parse(splits.Value) == 0)
         meshFlags |= MeshFlags.OptimizeDoNotSplit;
 }
Example #42
0
 public Mesh Clone(MeshFlags options, VertexFormats vertexFormat, Device device)
 {
     throw new NotImplementedException();
 }
Example #43
0
		/// <summary>
		/// Cone the mesh (and textures that it contains), 
		/// optionally converting the vertex and texture format.
		/// </summary>
		public AutoMesh Clone(Direct3d d3d, MeshFlags flags, VertexFormats vertexFormat,
						Format textureFormat, Usage usage, Pool pool)
		{
			// Clone the mesh vertex info
			Mesh mesh = mMesh.Clone(flags, vertexFormat, d3d.Dx);
			AutoMesh autoMesh = new AutoMesh(d3d, mesh);
			
			// Clone AutoMesh variables
			autoMesh.Tag = Tag;
			
			// Clone textures and materials
			if (mTextures.Length != 0)
			{
				// Clone materials
				autoMesh.mMaterials = new Material[mMaterials.Length];
				for (int i = 0;  i < mMaterials.Length;  i++)
					autoMesh.mMaterials[i] = mMaterials[i];
				
				// Clone textures
				autoMesh.mTextures = new AutoTexture[mTextures.Length];
				for (int i = 0;  i < mTextures.Length;  i++)
					if (mTextures[i] != null)
					{
						// Already cloned this texture?
						bool alreadyConvertedTexture = false;
						for (int j = 0;  j < i;  j++)
							if (mTextures[i] == mTextures[j])
							{
								alreadyConvertedTexture = true;
								autoMesh.mTextures[i] = autoMesh.mTextures[j];
								break;
							}
						// Clone new texture
						if (!alreadyConvertedTexture)
							autoMesh.mTextures[i] = mTextures[i].Clone(d3d, textureFormat, usage, pool);
					}
			}
			return autoMesh;			
		}
Example #44
0
 public PatchMesh Clone(MeshFlags options, VertexElement[] decl)
 {
     throw new NotImplementedException();
 }
Example #45
0
		/// <summary>
		/// Save the mesh when the DirectX device is lost
		/// </summary>
		void d3d_DxLost(Direct3d d3d, Device dx)
		{
            if (mMesh == null)
                return;

			// Save all data needed to restore the mesh
			mNumFaces = mMesh.NumberFaces;
			mNumVertices = mMesh.NumberVertices;
			mNumBytesPerVertex = mMesh.NumberBytesPerVertex;
			mFlags = mMesh.Options.Value;
			mVertexFormat = mMesh.VertexFormat;

			// Copy pathIndex buffer
			mIndexBufferCopy = (byte[])mMesh.LockIndexBuffer(typeof(byte),
										LockFlags.ReadOnly, mMesh.IndexBuffer.Description.Size);
			mMesh.UnlockIndexBuffer();

			// Copy vertex buffer
			mVertexBufferCopy = (byte[])mMesh.LockVertexBuffer(typeof(byte),
							LockFlags.ReadOnly, mMesh.NumberBytesPerVertex * mMesh.NumberVertices);
			mMesh.UnlockVertexBuffer();

			// Copy attribute buffer
			mAttributeBufferCopy = mMesh.LockAttributeBufferArray(LockFlags.ReadOnly);
			mMesh.UnlockAttributeBuffer(mAttributeBufferCopy);

			mMesh.Dispose();
			mMesh = null;
			mVertexCache = null;
		}
Example #46
0
 public static PatchMesh FromX(XFileData xofObjMesh, MeshFlags options, Device device, out ExtendedMaterial[] materials, out EffectInstance[] effects)
 {
     throw new NotImplementedException();
 }
Example #47
0
		/// <summary>
		/// Read a mesh from an X file, and load the textures which are
		/// assumed to be in the same directory.
		/// </summary>
		public static AutoMesh LoadFromXFile(string path, MeshFlags flags, Direct3d d3d)
		{
			ExtendedMaterial[] extendedMaterials;
			String []fileNames;
			AutoMesh mesh = new AutoMesh(d3d, Mesh.FromFile(path, 
										MeshFlags.SystemMemory, d3d.Dx, out extendedMaterials));

			mesh.mTextures = new AutoTexture[extendedMaterials.Length];
			mesh.mMaterials = new Material[extendedMaterials.Length];
			fileNames = new string[extendedMaterials.Length];
			
			// Load all the textures for this mesh
			for (int i = 0;  i < extendedMaterials.Length;  i++)
			{
				if (extendedMaterials[i].TextureFilename != null)
				{
					string textureFileName = System.IO.Path.Combine(
											System.IO.Path.GetDirectoryName(path), 
											extendedMaterials[i].TextureFilename);
					fileNames[i] = textureFileName;
					
					// Scan to see if we already have this texture
					bool alreadyHaveTexture = false;
					for (int j = 0;  j < i;  j++)
						if (textureFileName == fileNames[j])
						{
							mesh.mTextures[i] = mesh.mTextures[j];
							alreadyHaveTexture = true;
							break;
						}
					// Load texture (if we don't already have it)
					if (!alreadyHaveTexture)
						mesh.mTextures[i] = new AutoTexture(d3d, 
											TextureLoader.FromFile(d3d.Dx, textureFileName));
				}
				mesh.mMaterials[i] = extendedMaterials[i].Material3D;
				mesh.mMaterials[i].Ambient = mesh.mMaterials[i].Diffuse;
			}
			return mesh;
		}