Ejemplo n.º 1
0
        private void CalculateNormals()
        {
            VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[shipVertexBuffer.VertexCount];
            short[] indices = new short[indexbuffer.IndexCount];
            shipVertexBuffer.GetData(vertices);
            indexbuffer.GetData(indices);
            for (int x = 0; x < vertices.Length; x++)
            {
                vertices[x].Normal = Vector3.Zero;
            }
            int triangleCount = indices.Length / 3;

            for (int x = 0; x < triangleCount; x++)
            {
                int     v1             = indices[x * 3];
                int     v2             = indices[(x * 3) + 1];
                int     v3             = indices[(x * 3) + 2];
                Vector3 firstSide      = vertices[v2].Position - vertices[v1].Position;
                Vector3 secondSide     = vertices[v1].Position - vertices[v3].Position;
                Vector3 triangleNormal =
                    Vector3.Cross(firstSide, secondSide);
                triangleNormal.Normalize();
                vertices[v1].Normal += triangleNormal;
                vertices[v2].Normal += triangleNormal;
                vertices[v3].Normal += triangleNormal;
            }
            for (int x = 0; x < vertices.Length; x++)
            {
                vertices[x].Normal.Normalize();
            }

            shipVertexBuffer.SetData(vertices);
        }
Ejemplo n.º 2
0
        internal short[] GetIndices()
        {
            var list = new short[IndexBuffer.IndexCount];

            IndexBuffer.GetData(list);
            return(list);
        }
Ejemplo n.º 3
0
        internal Mesh Clone()
        {
            var geometryData = new GeometryData
            {
                Vertices = new VertexPositionNormalTexture[VertexCount], Indices = new ushort[IndexCount],
            };

            _vertexBuffer.GetData(geometryData.Vertices);
            _indexBuffer.GetData(geometryData.Indices);

            return(new Mesh(_vertexBuffer.GraphicsDevice, geometryData));
        }
Ejemplo n.º 4
0
    void UpdateMesh()
    {
        Tribuffer.SetCounterValue(0);

        // common
        marchingCS.SetInt("GridRes", GridRes);
        marchingCS.SetFloat("Time", Time.time);
        marchingCS.SetFloat("NoiseInterval", NoiseInterval);
        marchingCS.SetFloat("IsoLevel", IsoLevel);
        marchingCS.SetBool("EnableSmooth", EnableSmooth);
        marchingCS.SetVector("CenterPos", CenterPos);
        marchingCS.SetFloat("GridW", GridW);

        kernel = marchingCS.FindKernel("UpdateVoxel");
        marchingCS.SetTexture(kernel, "VoxelTexture", VoxelTexture);
        marchingCS.Dispatch(kernel, GridRes, GridRes, GridRes);

        kernel = marchingCS.FindKernel("CalculateTriangle");
        marchingCS.SetTexture(kernel, "VoxelTexture", VoxelTexture);
        marchingCS.SetBuffer(kernel, "Tribuffer", Tribuffer);
        marchingCS.Dispatch(kernel, GridRes / 8, GridRes / 8, GridRes / 8);

        ComputeBuffer.CopyCount(Tribuffer, CountBuffer, 0);
        int[] countArr = { 0 };
        CountBuffer.GetData(countArr);
        int count = countArr[0]; // the actual num

        if (count != 0)
        {
            kernel = marchingCS.FindKernel("ExtractData");
            marchingCS.SetInt("TriangleCount", count);
            marchingCS.SetBuffer(kernel, "NewTriBuffer", Tribuffer);
            marchingCS.SetBuffer(kernel, "PosBuffer", PosBuffer);
            marchingCS.SetBuffer(kernel, "NormalBuffer", NormalBuffer);
            marchingCS.SetBuffer(kernel, "IndexBuffer", IndexBuffer);
            marchingCS.Dispatch(kernel, (int)Mathf.Ceil(count / 10f), 1, 1);
        }

        Vector3[] posArr = new Vector3[count * 3];
        PosBuffer.GetData(posArr, 0, 0, count * 3);
        Vector3[] normalArr = new Vector3[count * 3];
        NormalBuffer.GetData(normalArr, 0, 0, count * 3);


        int[] indexArr = new int[count * 3];
        IndexBuffer.GetData(indexArr, 0, 0, count * 3);

        mesh.Clear();
        mesh.vertices  = posArr;
        mesh.normals   = normalArr;
        mesh.triangles = indexArr;
    }
Ejemplo n.º 5
0
        public void ShouldSetAndGetData()
        {
            Game.DrawWith += (sender, e) =>
            {
                var savedData   = new short[] { 1, 2, 3, 4 };
                var indexBuffer = new IndexBuffer(Game.GraphicsDevice, IndexElementSize.SixteenBits, savedData.Length, BufferUsage.None);
                indexBuffer.SetData(savedData);

                var readData = new short[4];
                indexBuffer.GetData(readData, 0, 4);
                Assert.AreEqual(savedData, readData);
            };
            Game.Run();
        }
Ejemplo n.º 6
0
        public void ShouldSetAndGetData()
        {
            var savedData   = new short[] { 1, 2, 3, 4 };
            var indexBuffer = new IndexBuffer(gd, IndexElementSize.SixteenBits, savedData.Length, BufferUsage.None);

            indexBuffer.SetData(savedData);

            var readData = new short[4];

            indexBuffer.GetData(readData, 0, 4);
            Assert.AreEqual(savedData, readData);

            indexBuffer.Dispose();
        }
Ejemplo n.º 7
0
        public void InitBuffers()
        {
            // Get mesh vertex data
            meshVertices = new VertexData[meshVertexBuffer.VertexCount];
            meshVertexBuffer.GetData <VertexData>(meshVertices);

            // Get mesh index data
            meshIndices = new short[meshIndexBuffer.IndexCount];
            meshIndexBuffer.GetData <short>(meshIndices);

            // Create vertex and index data arrays for instances
            vertices = new VertexData[meshVertices.Count() * maxAmountOfInstances];
            indices  = new short[meshIndices.Count() * maxAmountOfInstances];
        }
Ejemplo n.º 8
0
        public void ShouldSetAndGetData()
        {   
            Game.DrawWith += (sender, e) =>
            {
                var savedData = new short[] { 1, 2, 3, 4 };
                var indexBuffer = new IndexBuffer(Game.GraphicsDevice, IndexElementSize.SixteenBits, savedData.Length, BufferUsage.None);
                indexBuffer.SetData(savedData);

                var readData = new short[4];
                indexBuffer.GetData(readData, 0, 4);
                Assert.AreEqual(savedData, readData);
            };
            Game.Run();
        }
Ejemplo n.º 9
0
        public void ShouldSetAndGetData_offsetInBytes()
        {
            Game.DrawWith += (sender, e) =>
            {
                var savedData   = new short[] { 1, 2, 3, 4 };
                var indexBuffer = new IndexBuffer(Game.GraphicsDevice, IndexElementSize.SixteenBits, savedData.Length, BufferUsage.None);
                indexBuffer.SetData(savedData);

                var readData = new short[2];
                indexBuffer.GetData(sizeof(short) * 2, readData, 0, 2);
                Assert.AreEqual(3, readData[0]);
                Assert.AreEqual(4, readData[1]);
            };
            Game.Run();
        }
Ejemplo n.º 10
0
        public void ShouldSetAndGetData_offsetInBytes()
        {
            Game.DrawWith += (sender, e) =>
            {
                var savedData = new short[] { 1, 2, 3, 4 };
                var indexBuffer = new IndexBuffer(Game.GraphicsDevice, IndexElementSize.SixteenBits, savedData.Length, BufferUsage.None);
                indexBuffer.SetData(savedData);

                var readData = new short[2];
                indexBuffer.GetData(sizeof(short) * 2, readData, 0, 2);
                Assert.AreEqual(3, readData[0]);
                Assert.AreEqual(4, readData[1]);
            };
            Game.Run();
        }
Ejemplo n.º 11
0
        public void ShouldSetAndGetData_offsetInBytes()
        {
            var savedData   = new short[] { 1, 2, 3, 4 };
            var indexBuffer = new IndexBuffer(gd, IndexElementSize.SixteenBits, savedData.Length, BufferUsage.None);

            indexBuffer.SetData(savedData);

            var readData = new short[2];

            indexBuffer.GetData(sizeof(short) * 2, readData, 0, 2);
            Assert.AreEqual(3, readData[0]);
            Assert.AreEqual(4, readData[1]);

            indexBuffer.Dispose();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Build Lods from retrieved data.
        /// </summary>
        public void BuildLods(FrameGeometry frameGeometry, FrameMaterial frameMaterial, VertexBuffer[] vertexBuffers, IndexBuffer[] indexBuffers)
        {
            lods = new Lod[frameGeometry.NumLods];
            for (int i = 0; i != lods.Length; i++)
            {
                FrameLOD frameLod = frameGeometry.LOD[i];
                lods[i] = new Lod
                {
                    VertexDeclaration = frameGeometry.LOD[i].VertexDeclaration
                };
                IndexBuffer  indexBuffer  = indexBuffers[i];
                VertexBuffer vertexBuffer = vertexBuffers[i];

                int vertexSize;
                Dictionary <VertexFlags, FrameLOD.VertexOffset> vertexOffsets = frameLod.GetVertexOffsets(out vertexSize);
                lods[i].Vertices = new Vertex[frameLod.NumVerts];

                if (vertexSize * frameLod.NumVerts != vertexBuffer.Data.Length)
                {
                    throw new System.Exception();
                }
                for (int v = 0; v != lods[i].Vertices.Length; v++)
                {
                    //declare data required and send to decompresser
                    byte[] data = new byte[vertexSize];
                    Array.Copy(vertexBuffers[i].Data, (v * vertexSize), data, 0, vertexSize);
                    lods[i].Vertices[v] = VertexTranslator.DecompressVertex(data, frameGeometry.LOD[i].VertexDeclaration, frameGeometry.DecompressionOffset, frameGeometry.DecompressionFactor, vertexOffsets);
                }

                lods[i].Indices = indexBuffer.GetData();
                MaterialStruct[] materials = frameMaterial.Materials[i];
                lods[i].Parts = new ModelPart[materials.Length];
                for (int x = 0; x != materials.Length; x++)
                {
                    if (string.IsNullOrEmpty(materials[x].MaterialName))
                    {
                        var material = MaterialsManager.LookupMaterialByHash(materials[x].MaterialHash);
                        materials[x].MaterialName = material.GetMaterialName();
                    }

                    ModelPart modelPart = new ModelPart();
                    modelPart.Material   = materials[x].MaterialName;
                    modelPart.StartIndex = (uint)materials[x].StartIndex;
                    modelPart.NumFaces   = (uint)materials[x].NumFaces;
                    lods[i].Parts[x]     = modelPart;
                }
            }
        }
Ejemplo n.º 13
0
        public List <int> GetModelIndices()
        {
            if (indexBuffer.IndexElementSize != IndexElementSize.SixteenBits)
            {
                throw new Exception("Model uses 32-bit indices, which are not supported.");
            }

            int TriVertsCount = numPrimitives * 3;

            short[] s = new short[TriVertsCount];
            indexBuffer.GetData <short>(0, s, 0, TriVertsCount);
            List <int> indices = new List <int>();

            for (int i = 0; i != numPrimitives; ++i)
            {
                indices.Add(s[i * 3 + 0]);
                indices.Add(s[i * 3 + 1]);
                indices.Add(s[i * 3 + 2]);
            }

            return(indices);
        }
        public static void WriteIndexBuffer(TWXmlNode node, IndexBuffer indexBuffer)
        {
            if (indexBuffer == null)
            {
                node.Value = "NULL"; return;
            }
            byte[] data = new byte[indexBuffer.SizeInBytes];
            indexBuffer.GetData <byte>(data);

            if (data.Length != indexBuffer.SizeInBytes)
            {
                throw new Exception("While writing this method, i assumed those were equal");
            }

            node.AddChildNode("BufferUsage", indexBuffer.BufferUsage.ToString());
            node.AddChildNode("IndexElementSize", indexBuffer.IndexElementSize.ToString());
            TWXmlNode dataNode = node.CreateChildNode("Data");

            dataNode.AddAttribute("length", data.Length.ToString());

            //TODO: this data should be contained in a 'CData' block
            dataNode.AddCData(Convert.ToBase64String(data));
        }
Ejemplo n.º 15
0
        void CalculateNormals()
        {
            VertexPositionNormalTexture[] vertices =
                new VertexPositionNormalTexture[TheVBuffer.VertexCount];
            uint[] indices = new uint[TheIBuffer.IndexCount];
            TheVBuffer.GetData(vertices);
            TheIBuffer.GetData(indices);

            for (int i = 0; i < vertices.Length / 3; i++)
            {
                vertices[i].Normal = Vector3.Zero;
            }

            int triangleCount = indices.Length / 3;

            for (uint i = 0; i < triangleCount; i++)
            {
                uint    v1             = indices[i * 3];
                uint    v2             = indices[(i * 3) + 1];
                uint    v3             = indices[(i * 3) + 2];
                Vector3 firstSide      = vertices[v2].Position - vertices[v1].Position;
                Vector3 secondSide     = vertices[v1].Position - vertices[v3].Position;
                Vector3 triangleNormal = Vector3.Cross(firstSide, secondSide);
                triangleNormal.Normalize();
                vertices[v1].Normal += triangleNormal;
                vertices[v2].Normal += triangleNormal;
                vertices[v3].Normal += triangleNormal;
            }

            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i].Normal.Normalize();
            }

            TheVBuffer.SetData(vertices);
        }
 internal void Draw(PrimitiveType primitiveType, GraphicsDevice graphicsDevice, Effect effect)
 {
     int proposedVertexSize = Math.Max(vertexCount, MIN_SIZE);
     while (proposedVertexSize < vertexCount + pendingVertices.Count)
     {
         proposedVertexSize = (int)(proposedVertexSize * GROWTH_FACTOR);
     }
     if (vertexBuffer == null || proposedVertexSize > vertexBuffer.VertexCount)
     {
         T[] newVertexData = new T[proposedVertexSize];
         VertexBuffer newVertexBuffer = new VertexBuffer(graphicsDevice, new T().VertexDeclaration, newVertexData.Length, BufferUsage.None);
         if (vertexBuffer != null)
         {
             vertexBuffer.GetData(newVertexData, 0, vertexCount);
             vertexBuffer.Dispose();
         }
         for (int i = 0; i < pendingVertices.Count; i++)
         {
             newVertexData[vertexCount + i] = pendingVertices[i];
         }
         vertexCount += pendingVertices.Count;
         pendingVertices.Clear();
         newVertexBuffer.SetData(newVertexData);
         vertexBuffer = newVertexBuffer;
     }
     int proposedIndexCount = Math.Max(indexCount, MIN_SIZE);
     while (proposedIndexCount < indexCount + pendingIndices.Count)
     {
         proposedIndexCount = (int)(proposedIndexCount * GROWTH_FACTOR);
     }
     if (indexBuffer == null || proposedIndexCount > indexBuffer.IndexCount)
     {
         int[] newIndexData = new int[proposedIndexCount];
         IndexBuffer newIndexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.ThirtyTwoBits, newIndexData.Length, BufferUsage.None);
         if (indexBuffer != null)
         {
             indexBuffer.GetData(newIndexData, 0, indexCount);
             indexBuffer.Dispose();
         }
         for (int i = 0; i < pendingIndices.Count; i++)
         {
             newIndexData[indexCount + i] = pendingIndices[i];
         }
         indexCount += pendingIndices.Count;
         pendingIndices.Clear();
         newIndexBuffer.SetData(newIndexData);
         indexBuffer = newIndexBuffer;
     }
     if (indexCount > 0)
     {
         graphicsDevice.SetVertexBuffer(vertexBuffer);
         graphicsDevice.Indices = indexBuffer;
         foreach (EffectPass pass in effect.CurrentTechnique.Passes)
         {
             pass.Apply();
             switch (primitiveType)
             {
                 case PrimitiveType.TriangleList:
                     graphicsDevice.DrawIndexedPrimitives(primitiveType, 0, 0, indexCount / 3);
                     break;
                 case PrimitiveType.LineList:
                     graphicsDevice.DrawIndexedPrimitives(primitiveType, 0, 0, indexCount / 2);
                     break;
             }
         }
     }
 }
Ejemplo n.º 17
0
        public static InstancedIndexBuffer Create( IndexBuffer orignalIndexBuffer,
            int leastInstances, bool allow32bitIndex)
        {
            if ( orignalIndexBuffer.IndexElementSize != IndexElementSize.SixteenBits )
              {
            throw new ArgumentOutOfRangeException( "32-bit index buffer is not supported." );
              }

              GraphicsDevice gd = orignalIndexBuffer.GraphicsDevice;

              int indexCount = orignalIndexBuffer.SizeInBytes / sizeof( ushort );
              ushort[] originalIndices = new ushort[indexCount];
              orignalIndexBuffer.GetData<ushort>( originalIndices );

              int instanceCount = Math.Max( ushort.MaxValue / indexCount, leastInstances );

              int newSize = instanceCount * indexCount;

              InstancedIndexBuffer indexBuffer = null;

              if ( newSize >= ushort.MaxValue )
              {
            if ( allow32bitIndex == false )
            {
              throw new InvalidOperationException(
              "Number of indices cannot fit in a 16-bit index buffer." +
              "HWInstancePart.cs, Allow32BitIndexBuffer should be true." +
              "Or reduce the number of vertices in the model and pray." );
            }

            uint[] newIndices = new uint[newSize];

            int index = 0;
            for ( int i = 0; i < instanceCount; ++i )
            {
              uint packInstanceValue = (uint)( i * indexCount );

              for ( int j = 0; j < originalIndices.Length; ++j )
            newIndices[index++] = packInstanceValue + originalIndices[j];
            }

            indexBuffer = new InstancedIndexBuffer( gd, newSize * sizeof( uint ),
                                                IndexElementSize.ThirtyTwoBits );

            indexBuffer.SetData<uint>( newIndices );
              }
              else
              {
            // using 16-bit index buffer
            ushort[] newIndices = new ushort[newSize];

            int index = 0;
            for ( int i = 0; i < instanceCount; ++i )
            {
              ushort packInstanceValue = (ushort)( i * indexCount );

              for ( int j = 0; j < originalIndices.Length; ++j )
              {
            newIndices[index++] =
                (ushort)( packInstanceValue + originalIndices[j] );
              }
            }

            indexBuffer = new InstancedIndexBuffer( gd, newSize * sizeof( ushort ),
                                                IndexElementSize.SixteenBits );

            indexBuffer.SetData<ushort>( newIndices );
              }

              indexBuffer.MaxInstances = instanceCount;

              return indexBuffer;
        }
Ejemplo n.º 18
0
        bool IDeviceIndexBuffer.AllocateForInstancing(DrawState state)
        {
            if (buffer.instancingCount > 0)
            {
                return(buffer.instancingCount > 1);
            }

            int instances = 128;

            if (this.buffer.Count > 100)
            {
                instances = 64;
            }
            if (this.buffer.Count > 2000)
            {
                instances = 32;
            }
            if (this.buffer.Count > 20000)
            {
                instances = 16;
            }
            if (this.buffer.Count > 175000)
            {
                instances = 8;
            }
            if (this.buffer.Count > 250000)
            {
                instances = 4;
            }
            if (this.buffer.Count > 300000)
            {
                instances = 2;
            }
            if (this.buffer.Count > 400000)
            {
                instances = 1;
            }

            if ((this.ResourceUsage & ResourceUsage.Dynamic) == ResourceUsage.Dynamic)
            {
                instances = 1;
            }

            bool convertToInt = false;

            if (instances > 1)
            {
                if (this.buffer.Stride == 2)
                {
                    if (typeof(IndexType) == typeof(ushort))
                    {
                        if ((this.buffer.i_max + 1) * instances > ushort.MaxValue)
                        {
                            if ((int)ushort.MaxValue / (this.buffer.i_max + 1) >= 16)
                            {
                                instances = (int)ushort.MaxValue / (this.buffer.i_max + 1);
                            }
                            else
                            {
                                convertToInt = true;
                            }
                        }
                    }
                    else
                    {
                        if (this.buffer.i_max * instances > short.MaxValue)
                        {
                            if ((int)short.MaxValue / (this.buffer.i_max + 1) >= 16)
                            {
                                instances = (int)short.MaxValue / (this.buffer.i_max + 1);
                            }
                            else
                            {
                                convertToInt = true;
                            }
                        }
                    }
                }
                else
                {
                    if ((this.buffer.i_max + 1) * 64 > state.graphics.GraphicsDeviceCapabilities.MaxVertexIndex)
                    {
                        instances = Math.Max(1, state.graphics.GraphicsDeviceCapabilities.MaxVertexIndex / (this.buffer.i_max + 1));
                    }
                }
            }

            buffer.instancingCount = 1;

            if (instances > 1)
            {
                IEnumerable <IndexType> data = buffer.Data;

                if (ib != null)
                {
                    if (data == null)
                    {
                        data = new IndexType[buffer.Count];
                        ib.GetData <IndexType>((IndexType[])data);
                    }
                    ib.Dispose();
                    ib = null;
                }
                if (data == null)
                {
                    buffer.instancingCount = 1;
                    return(false);
                }

                buffer.Dispose();

                buffer = new Implementation(data);
                buffer.instancingCount = instances;
                buffer.convertToInt    = convertToInt;
            }
            return(buffer.instancingCount > 1);
        }