当前位置: 首页>>代码示例>>C#>>正文


C# Mesh.LockIndexBuffer方法代码示例

本文整理汇总了C#中Mesh.LockIndexBuffer方法的典型用法代码示例。如果您正苦于以下问题:C# Mesh.LockIndexBuffer方法的具体用法?C# Mesh.LockIndexBuffer怎么用?C# Mesh.LockIndexBuffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Mesh的用法示例。


在下文中一共展示了Mesh.LockIndexBuffer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CreateMesh

        protected override BulletMesh CreateMesh(Device device)
        {
            int totalTriangles = this.indices.Length /3;
            int totalVerts = this.vertices.Length;

            Mesh m = new Mesh(device, totalTriangles, totalVerts, MeshFlags.Use32Bit | MeshFlags.SystemMemory, VertexFormat.Position | VertexFormat.Normal);
            SlimDX.DataStream data = m.LockVertexBuffer(LockFlags.None);
            for (int i = 0; i < this.vertices.Length; i++)
            {
                    data.Write(this.vertices[i].X);
                    data.Write(this.vertices[i].Y);
                    data.Write(this.vertices[i].Z);

                    data.Write(0.0f);
                    data.Write(0.0f);
                    data.Write(0.0f);

                    //data.Write(this.texcoords[i]);

            }
            m.UnlockVertexBuffer();

            data = m.LockIndexBuffer(LockFlags.None);
            for (int i = 0; i < this.indices.Length; i++)
            {
                data.Write(this.indices[i]);
            }
            m.UnlockIndexBuffer();
            m.ComputeNormals();
            return null;// new BulletMesh(m);
        }
开发者ID:sunep,项目名称:dx11-vvvv,代码行数:31,代码来源:ConvexHullShapeDefinition.cs

示例2: Terrain

        /// <summary>
        /// Constructor for randomly generating terrian
        /// </summary>
        public Terrain()
        {
            //FileStream fs = new FileStream("heightdata.raw", FileMode.Open, FileAccess.Read);
            //BinaryReader r = new BinaryReader(fs);
            rand = new Random();

            width = rand.Next(2, 100);//64;//rand.Next(2, 50);
            tall = rand.Next(2, 100);//64;//rand.Next(2, 50);
            world = Matrix.Identity;

            Height = new int[width, tall];

            var vertices = new CustomVertex.VertexPositionColor[width * tall];
            var indicies = new short[(width - 1) * (tall - 1) * 3];

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < tall; j++)
                {
                    //height[width - 1 - j, tall - 1 - i] = (int)(r.ReadByte() / 50);
                    Height[i, j] = rand.Next(0, 3);
                }
            }

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < tall; j++)
                {
                    vertices[i + j * width].Position = new Vector3(i, Height[i, j], j);
                    vertices[i + j * width].Color = Color.White.ToArgb();
                }
            }

            for (int i = 0; i < width - 1; i++)
            {
                for (int j = 0; j < tall - 1; j++)
                {
                    indicies[(i + j * (width - 1)) * 3] = (short)((i + 1) + (j + 1) * width);
                    indicies[(i + j * (width - 1)) * 3 + 1] = (short)((i + 1) + j * width);
                    indicies[(i + j * (width - 1)) * 3 + 2] = (short)(i + j * width);
                }
            }

            mesh = new Mesh(DeviceManager.LocalDevice, indicies.Length, vertices.Length,
                MeshFlags.Managed, CustomVertex.VertexPositionColor.Format);

            mesh.LockVertexBuffer(LockFlags.Discard).WriteRange<CustomVertex.VertexPositionColor>(vertices);
            mesh.UnlockVertexBuffer();

            mesh.LockIndexBuffer(LockFlags.Discard).WriteRange<short>(indicies);
            mesh.UnlockIndexBuffer();

            mesh.Optimize(MeshOptimizeFlags.AttributeSort | MeshOptimizeFlags.Compact);

            //r.Dispose();
            //fs.Dispose();
        }
开发者ID:senbeiwabaka,项目名称:Computer-Graphics-Project,代码行数:60,代码来源:Terrain.cs

示例3: CreateShape

        Mesh CreateShape(CollisionShape shape)
        {
            uint[] indices;
            BulletSharp.Math.Vector3[] vertices = CreateShape(shape, out indices);

            int vertexCount = vertices.Length / 2;
            int indexCount = (indices != null) ? indices.Length : vertexCount;
            bool index32 = indexCount > 65536;

            Mesh mesh = new Mesh(device, indexCount / 3, vertexCount,
                MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal);

            DataStream vertexBuffer = mesh.LockVertexBuffer(LockFlags.Discard);
            vertexBuffer.WriteRange(vertices);
            mesh.UnlockVertexBuffer();

            DataStream indexBuffer = mesh.LockIndexBuffer(LockFlags.Discard);
            if (index32)
            {
                if (indices == null)
                {
                    indices = new uint[indexCount];
                    uint i = 0;
                    while (i < indexCount)
                    {
                        indices[i] = i;
                        i++;
                    }
                }
                indexBuffer.WriteRange(indices);
            }
            else
            {
                ushort[] indices_s;
                if (indices == null)
                {
                    indices_s = new ushort[indexCount];
                    ushort i = 0;
                    while (i < indexCount)
                    {
                        indices_s[i] = i;
                        i++;
                    }
                }
                else
                {
                    indices_s = CompactIndexBuffer(indices);
                }
                indexBuffer.WriteRange(indices_s);
            }
            mesh.UnlockIndexBuffer();

            shapes.Add(shape, mesh);
            return mesh;
        }
开发者ID:rhynodegreat,项目名称:BulletSharpPInvoke,代码行数:55,代码来源:MeshFactory.cs

示例4: RenderSoftBodyTextured

        public void RenderSoftBodyTextured(SoftBody softBody)
        {
            if (!(softBody.UserObject is Array))
                return;

            object[] userObjArr = softBody.UserObject as object[];
            FloatArray vertexBuffer = userObjArr[0] as FloatArray;
            IntArray indexBuffer = userObjArr[1] as IntArray;

            int vertexCount = (vertexBuffer.Count / 8);

            if (vertexCount > 0)
            {
                int faceCount = indexBuffer.Count / 2;

                bool index32 = vertexCount > 65536;

                Mesh mesh = new Mesh(device, faceCount, vertexCount,
                    MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0),
                    VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1);

                DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard);
                if (index32)
                {
                    foreach (int i in indexBuffer)
                        indices.Write(i);
                }
                else
                {
                    foreach (int i in indexBuffer)
                        indices.Write((short)i);
                }
                mesh.UnlockIndexBuffer();

                DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard);
                foreach (float f in vertexBuffer)
                    verts.Write(f);
                mesh.UnlockVertexBuffer();

                mesh.ComputeNormals();
                mesh.DrawSubset(0);
                mesh.Dispose();
            }
        }
开发者ID:WebFreak001,项目名称:BulletSharp,代码行数:44,代码来源:MeshFactory.cs

示例5: CreateConvexHullShape

        Mesh CreateConvexHullShape(ConvexHullShape shape)
        {
            ShapeHull hull = new ShapeHull(shape);
            hull.BuildHull(shape.Margin);

            UIntArray hullIndices = hull.Indices;
            Vector3Array points = hull.Vertices;


            int vertexCount = hull.NumIndices;
            int faceCount = hull.NumTriangles;

            bool index32 = vertexCount > 65536;

            Mesh mesh = new Mesh(device, faceCount, vertexCount,
                MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal);


            SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard);
            int i;
            if (index32)
            {
                for (i = 0; i < vertexCount; i++)
                    indices.Write(i);
            }
            else
            {
                for (i = 0; i < vertexCount; i++)
                    indices.Write((short)i);
            }
            mesh.UnlockIndexBuffer();

            SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard);
            Vector3 scale = Vector3.Multiply(shape.LocalScaling, 1.0f + shape.Margin);
            for (i = 0; i < vertexCount; i += 3)
            {
                verts.Write(Vector3.Modulate(points[(int)hullIndices[i]], scale));
                verts.Position += 12;
                verts.Write(Vector3.Modulate(points[(int)hullIndices[i+1]], scale));
                verts.Position += 12;
                verts.Write(Vector3.Modulate(points[(int)hullIndices[i+2]], scale));
                verts.Position += 12;
            }
            mesh.UnlockVertexBuffer();

            mesh.ComputeNormals();
            shapes.Add(shape, mesh);

            return mesh;
        }
开发者ID:rhynodegreat,项目名称:BulletSharp,代码行数:50,代码来源:GraphicObjectFactory.cs

示例6: AtmoSphere

        /// <summary>
        /// Creates a PositionColored sphere centered on zero, color is computed to render
        /// some kind of gas giant atmospheric glow - with saturn in mind ;)
        /// </summary>
        /// <param name="device">The current direct3D drawing device.</param>
        /// <param name="radius">The sphere's radius</param>
        /// <param name="slices">Number of slices (Horizontal resolution).</param>
        /// <param name="stacks">Number of stacks. (Vertical resolution)</param>
        /// <returns></returns>
        /// <remarks>
        /// Number of vertices in the sphere will be (slices+1)*(stacks+1)<br/>
        /// Number of faces     :slices*stacks*2
        /// Number of Indexes   : Number of faces * 3;
        /// </remarks>
        private Mesh AtmoSphere(Microsoft.DirectX.Direct3D.Device device, float radius, int slices, int stacks)
        {
            int numVertices = (slices + 1) * (stacks + 1);
            int numFaces = slices * stacks * 2;
            int indexCount = numFaces * 3;

            Mesh mesh = new Mesh(numFaces, numVertices, MeshFlags.Managed, CustomVertex.PositionColored.Format, device);

            // Get the original sphere's vertex buffer.
            int[] ranks = new int[1];
            ranks[0] = mesh.NumberVertices;
            System.Array arr = mesh.VertexBuffer.Lock(0, typeof(CustomVertex.PositionColored), LockFlags.None, ranks);

            // Set the vertex buffer
            int vertIndex = 0;
            for (int stack = 0; stack <= stacks; stack++)
            {
                double latitude = -90 + ((float)stack / stacks * (float)180.0);
                for (int slice = 0; slice <= slices; slice++)
                {
                    CustomVertex.PositionColored pnt = new CustomVertex.PositionColored();
                    double longitude = 180 - ((float)slice / slices * (float)360);
                    Vector3 v = MathEngine.SphericalToCartesian(latitude, longitude, radius);
                    pnt.X = v.X;
                    pnt.Y = v.Y;
                    pnt.Z = v.Z;
                    // Compute alpha according to sun angle and lat/lon
                    double sunAngle = MathEngine.SphericalDistanceDegrees(latitude, longitude, sunLat, sunLon);
                    // Winter pole glow
                    double alphaWinter = 0;
                    if (latitude * sunLat < 0)
                    { // opposite hemisphere from the sun
                        double sinLat = Math.Sin(MathEngine.DegreesToRadians(Math.Abs(latitude)));
                        double sinSun = Math.Sin(MathEngine.DegreesToRadians(Math.Abs(sunLat)));
                        double coefLat = Math.Abs(latitude / 90);
                        alphaWinter = 255;
                        alphaWinter *= sinLat;
                        alphaWinter *= sinSun * 2;
                        if (alphaWinter > 255) alphaWinter = 255;
                        if (alphaWinter < 0) alphaWinter = 0;
                        alphaWinter *= 0.7;
                    }
                    // day/night transition
                    double alphaTrans = 0;
                    alphaTrans = 100 * (1 - Math.Cos(MathEngine.DegreesToRadians(sunAngle)));
                    // final alpha
                    double alpha = Math.Max(alphaWinter, alphaTrans);
                    pnt.Color = Color.FromArgb((int)alpha, 0x10, 0x30, 0x90).ToArgb(); // glow color

                    arr.SetValue(pnt, vertIndex++);
                }
            }

            mesh.VertexBuffer.Unlock();
            ranks[0] = indexCount;
            arr = mesh.LockIndexBuffer(typeof(short), LockFlags.None, ranks);
            int i = 0;
            short bottomVertex = 0;
            short topVertex = 0;
            for (short x = 0; x < stacks; x++)
            {
                bottomVertex = (short)((slices + 1) * x);
                topVertex = (short)(bottomVertex + slices + 1);
                for (int y = 0; y < slices; y++)
                {
                    arr.SetValue(bottomVertex, i++);
                    arr.SetValue(topVertex, i++);
                    arr.SetValue((short)(topVertex + 1), i++);
                    arr.SetValue(bottomVertex, i++);
                    arr.SetValue((short)(topVertex + 1), i++);
                    arr.SetValue((short)(bottomVertex + 1), i++);
                    bottomVertex++;
                    topVertex++;
                }
            }
            mesh.IndexBuffer.SetData(arr, 0, LockFlags.None);

            return mesh;
        }
开发者ID:jpespartero,项目名称:WorldWind,代码行数:93,代码来源:PlanetaryRings.cs

示例7: CreateTriangleMeshShape

        Mesh CreateTriangleMeshShape(TriangleMeshShape shape)
        {
            StridingMeshInterface meshInterface = shape.MeshInterface;

            BulletSharp.DataStream verts, indices;
            int numVerts, numFaces;
            PhyScalarType vertsType, indicesType;
            int vertexStride, indexStride;
            meshInterface.GetLockedReadOnlyVertexIndexData(out verts, out numVerts, out vertsType, out vertexStride,
                out indices, out indexStride, out numFaces, out indicesType);

            bool index32 = numVerts > 65536;

            Mesh mesh = new Mesh(device, numFaces, numVerts,
                 MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal);

            SlimDX.DataStream data = mesh.LockVertexBuffer(LockFlags.None);
            while (verts.Position < verts.Length)
            {
                Vector3 v = verts.Read<Vector3>();
                data.Write(v);

                verts.Position += vertexStride - 12;

                // Normals will be calculated later
                data.Position += 12;
            }
            mesh.UnlockVertexBuffer();

            data = mesh.LockIndexBuffer(LockFlags.None);
            while (indices.Position < indices.Length)
            {
                int index = indices.Read<int>();
                if (index32)
                    data.Write(index);
                else
                    data.Write((short)index);
            }
            mesh.UnlockVertexBuffer();

            mesh.ComputeNormals();

            shapes.Add(shape, mesh);
            return mesh;
        }
开发者ID:rhynodegreat,项目名称:BulletSharp,代码行数:45,代码来源:GraphicObjectFactory.cs

示例8: LoadStars


//.........这里部分代码省略.........
					// compute aparent magnitude -1.5 - 10 to grayscale 0 - 255
					double VM = Convert.ToDouble(Vmag.Replace(".", DecSep));
					double Vdec = 255 - ((VM + 1.5) * 255 / 10);
					if(Vdec > maxVdec) maxVdec = Vdec;
					Vdec += 20; // boost luminosity
					if(Vdec > 255) Vdec = 255;
					// convert B-V  -0.5 - 4 for rgb color select
					double BVdec = 0;
					try {BVdec = Convert.ToDouble(BV.Replace(".", DecSep));}
					catch {BVdec = 0;}
					if(BVdec > maxBVdec) maxBVdec = BVdec;
					if(BVdec < minBVdec) minBVdec = BVdec;
					
					// Place vertex for point star
					v = MathEngine.SphericalToCartesian( latitude, longitude, sphereRadius);			
					verts[idx].Position = new Vector3( v.X, v.Y, v.Z );
					// color based on B-V
					verts[idx].Color = Color.FromArgb(255, (int)Vdec, (int)Vdec, (int)Vdec).ToArgb(); // gray scale default
					if(BVdec < 4)   verts[idx].Color = Color.FromArgb(255, (int)(235*Vdec/255), (int)(96*Vdec/255), (int)(10*Vdec/255)).ToArgb(); // redish
					if(BVdec < 1.5) verts[idx].Color = Color.FromArgb(255, (int)(246*Vdec/255), (int)(185*Vdec/255), (int)(20*Vdec/255)).ToArgb(); // orange
					if(BVdec < 1)   verts[idx].Color = Color.FromArgb(255, (int)(255*Vdec/255), (int)(251*Vdec/255), (int)(68*Vdec/255)).ToArgb(); // yellow
					if(BVdec < .5)  verts[idx].Color = Color.FromArgb(255, (int)(255*Vdec/255), (int)(255*Vdec/255), (int)(255*Vdec/255)).ToArgb(); // white
					if(BVdec < 0)   verts[idx].Color = Color.FromArgb(255, (int)(162*Vdec/255), (int)(195*Vdec/255), (int)(237*Vdec/255)).ToArgb(); // light blue

					// Next vertex
					idx++;

					// if flare add 4 vertex to mesh
					if(VM < FlareMag) 
					{
						double flareFactor = sphereRadius * 5 / drawArgs.device.Viewport.Width;
						double l = (VM + 1.5) / (FlareMag + 1.5) * flareFactor;	// Size of half flare texture in meter
						// Calculate perp1 and perp2 so they form a plane perpendicular to the star vector and crossing earth center
						Vector3 perp1 = Vector3.Cross( v, new Vector3(1,1,1) );
						Vector3 perp2 = Vector3.Cross( perp1, v );
						perp1.Normalize();
						perp2.Normalize();
						perp1.Scale((float)l);
						perp2.Scale((float)l);
						Vector3 v1;

						//v = MathEngine.SphericalToCartesian( latitude + l, longitude - l, sphereRadius);			
						v1 = v + perp1 - perp2;
						pnt = new CustomVertex.PositionTextured();
						pnt.Position = new Vector3( v1.X, v1.Y, v1.Z );
						pnt.Tu = 0;
						pnt.Tv = 0;
						arr.SetValue(pnt,vertIndex++);
						//v = MathEngine.SphericalToCartesian( latitude + l, longitude + l, sphereRadius);			
						v1 = v + perp1 + perp2;
						pnt = new CustomVertex.PositionTextured();
						pnt.Position = new Vector3( v1.X, v1.Y, v1.Z );
						pnt.Tu = 1;
						pnt.Tv = 0;
						arr.SetValue(pnt,vertIndex++);
						//v = MathEngine.SphericalToCartesian( latitude - l, longitude - l, sphereRadius);			
						v1 = v - perp1 - perp2;
						pnt = new CustomVertex.PositionTextured();
						pnt.Position = new Vector3( v1.X, v1.Y, v1.Z );
						pnt.Tu = 0;
						pnt.Tv = 1;
						arr.SetValue(pnt,vertIndex++);
						//v = MathEngine.SphericalToCartesian( latitude - l, longitude + l, sphereRadius);			
						v1 = v - perp1 + perp2;
						pnt = new CustomVertex.PositionTextured();
						pnt.Position = new Vector3( v1.X, v1.Y, v1.Z );
						pnt.Tu = 1;
						pnt.Tv = 1;
						arr.SetValue(pnt,vertIndex++);
					}
					

				}
				if(line.Substring(0, 3) == "---") isData = 1;
			}
			tr.Close();
			//MessageBox.Show("FlareCount : " + FlareCount.ToString(), "Info", MessageBoxButtons.OK, MessageBoxIcon.Error );


			// Set vertex buffer for stars
			StarListVB.SetData( verts, 0, LockFlags.None );

			// Set flare mesh indices
			FlareMesh.VertexBuffer.Unlock();
			ranks[0] = numFaces * 3;
			arr = FlareMesh.LockIndexBuffer(typeof(short),LockFlags.None,ranks);
			vertIndex = 0;
			for(int flare = 0; flare < FlareCount; flare++)
			{
				short v1 = (short)(flare * 4);
				arr.SetValue(v1, vertIndex++);
				arr.SetValue((short)(v1 + 1), vertIndex++);
				arr.SetValue((short)(v1 + 2),vertIndex++);
				arr.SetValue((short)(v1 + 1), vertIndex++);
				arr.SetValue((short)(v1 + 3), vertIndex++);
				arr.SetValue((short)(v1 + 2),vertIndex++);
			}
			FlareMesh.IndexBuffer.SetData(arr,0,LockFlags.None);
            FlareMesh.UnlockIndexBuffer();
        }
开发者ID:jpespartero,项目名称:WorldWind,代码行数:101,代码来源:Stars3D.cs

示例9: CreateFrame

        private AnimationFrame CreateFrame(xxFrame frame, xxParser parser, HashSet<string> extractFrames, HashSet<string> meshNames, Device device, Matrix combinedParent, List<AnimationFrame> meshFrames)
        {
            AnimationFrame animationFrame = new AnimationFrame();
            animationFrame.Name = frame.Name;
            animationFrame.TransformationMatrix = frame.Matrix;
            animationFrame.OriginalTransform = animationFrame.TransformationMatrix;
            animationFrame.CombinedTransform = combinedParent * animationFrame.TransformationMatrix;

            xxMesh mesh = frame.Mesh;
            if (meshNames.Contains(frame.Name) && (mesh != null))
            {
                List<xxBone> boneList = mesh.BoneList;

                string[] boneNames = new string[boneList.Count];
                Matrix[] boneOffsets = new Matrix[boneList.Count];
                for (int i = 0; i < boneList.Count; i++)
                {
                    xxBone bone = boneList[i];
                    boneNames[i] = bone.Name;
                    boneOffsets[i] = bone.Matrix;
                }

                AnimationMeshContainer[] meshContainers = new AnimationMeshContainer[mesh.SubmeshList.Count];
                Vector3 min = new Vector3(Single.MaxValue);
                Vector3 max = new Vector3(Single.MinValue);
                for (int i = 0; i < mesh.SubmeshList.Count; i++)
                {
                    xxSubmesh submesh = mesh.SubmeshList[i];
                    List<xxFace> faceList = submesh.FaceList;
                    List<xxVertex> vertexList = submesh.VertexList;

                    Mesh animationMesh = new Mesh(device, faceList.Count, vertexList.Count, MeshFlags.Managed, PositionBlendWeightsIndexedNormalTexturedColoured.Format);

                    using (DataStream indexStream = animationMesh.LockIndexBuffer(LockFlags.None))
                    {
                        for (int j = 0; j < faceList.Count; j++)
                        {
                            ushort[] indices = faceList[j].VertexIndices;
                            indexStream.Write(indices[0]);
                            indexStream.Write(indices[2]);
                            indexStream.Write(indices[1]);
                        }
                        animationMesh.UnlockIndexBuffer();
                    }

                    FillVertexBuffer(animationMesh, vertexList, -1);

                    var normalLines = new PositionBlendWeightsIndexedColored[vertexList.Count * 2];
                    for (int j = 0; j < vertexList.Count; j++)
                    {
                        xxVertex vertex = vertexList[j];

                        normalLines[j * 2] = new PositionBlendWeightsIndexedColored(vertex.Position, vertex.Weights3, vertex.BoneIndices, Color.Yellow.ToArgb());
                        normalLines[(j * 2) + 1] = new PositionBlendWeightsIndexedColored(vertex.Position + (vertex.Normal / 16), vertex.Weights3, vertex.BoneIndices, Color.Yellow.ToArgb());

                        min = Vector3.Minimize(min, vertex.Position);
                        max = Vector3.Maximize(max, vertex.Position);
                    }

                    AnimationMeshContainer meshContainer = new AnimationMeshContainer();
                    meshContainer.Name = animationFrame.Name;
                    meshContainer.MeshData = new MeshData(animationMesh);
                    meshContainer.NormalLines = normalLines;
                    meshContainers[i] = meshContainer;

                    int matIdx = submesh.MaterialIndex;
                    if ((matIdx >= 0) && (matIdx < parser.MaterialList.Count))
                    {
                        int texIdx;
                        if (!MatTexIndices.TryGetValue(matIdx, out texIdx))
                        {
                            texIdx = -1;

                            xxMaterial mat = parser.MaterialList[matIdx];
                            Material materialD3D = new Material();
                            materialD3D.Ambient = mat.Ambient;
                            materialD3D.Diffuse = mat.Diffuse;
                            materialD3D.Emissive = mat.Emissive;
                            materialD3D.Specular = mat.Specular;
                            materialD3D.Power = mat.Power;
                            Materials[matIdx] = materialD3D;

                            xxMaterialTexture matTex = mat.Textures[0];
                            string matTexName = matTex.Name;
                            if (matTexName != String.Empty)
                            {
                                for (int j = 0; j < parser.TextureList.Count; j++)
                                {
                                    xxTexture tex = parser.TextureList[j];
                                    if (tex.Name == matTexName)
                                    {
                                        texIdx = j;
                                        if (Textures[j] == null)
                                        {
                                            ImportedTexture importedTex = xx.ImportedTexture(tex);
                                            Textures[j] = Texture.FromMemory(device, importedTex.Data);
                                        }
                                        break;
                                    }
                                }
//.........这里部分代码省略.........
开发者ID:anhlehoang410,项目名称:SB3Utility,代码行数:101,代码来源:RenderObjectXX.cs

示例10: BasicSetup

        private unsafe void BasicSetup(byte[] data, string tex0)
        {
            LoadReturn lr=Load(data, data.Length);
            if(lr.Subsets<=0) throw new ApplicationException("Failed to load nif");
            subsets=new Subset[lr.Subsets];
            radius=lr.maxsize;
            loadLog=new string(lr.log);
            if(lr.FailedSubsets>0) System.Windows.Forms.MessageBox.Show(""+lr.FailedSubsets+" could not be rendered", "Warning");

            string texFileName;
            for(uint i=0;i<subsets.Length;i++) {
                //Get basic info
                GetInfo(i, out subsets[i].info);
                GetMaterial(i, out subsets[i].mat);
                GetTransform(i, out subsets[i].transform);
                if(i==0&&tex0!=null) texFileName=tex0;
                else if(subsets[i].info.containsTexture) {
                    sbyte* charPtr;
                    GetTex(i, out charPtr);
                    texFileName=new string(charPtr);
                } else texFileName=null;

                //sanity check
                //if(!subsets[i].info.containsTexCoords) throw new ApplicationException("Vertex texture coords are missing from subset "+i);
                //if(!subsets[i].info.containsNormals) throw new ApplicationException("Vertex normals are missing from subset "+i);
                //if(texFileName==null) throw new ApplicationException("No texture name was specified in subset "+i);

                //Load textures
                if(texFileName!=null) {
                    System.IO.Stream stream=BSAArchive.GetTexture(texFileName);
                    if(stream!=null) {
                        subsets[i].colorMap=TextureLoader.FromStream(device, stream);
                        SurfaceDescription desc=subsets[i].colorMap.GetLevelDescription(0);
                        subsets[i].data.cWidth=desc.Width;
                        subsets[i].data.cHeight=desc.Height;
                        subsets[i].data.cformat=desc.Format;
                        subsets[i].data.path=texFileName;
                    } else throw new ApplicationException("Could not load texture for subset "+i);
                    stream=BSAArchive.GetGlowTexture(texFileName);
                    if(stream!=null) {
                        subsets[i].glowMap=TextureLoader.FromStream(device, stream);
                        SurfaceDescription desc=subsets[i].glowMap.GetLevelDescription(0);
                        subsets[i].data.gWidth=desc.Width;
                        subsets[i].data.gHeight=desc.Height;
                        subsets[i].data.gformat=desc.Format;
                    } else subsets[i].data.gWidth=-1;
                    stream=BSAArchive.GetNormalTexture(texFileName);
                    if(stream!=null) {
                        subsets[i].normalMap=TextureLoader.FromStream(device, stream);
                        SurfaceDescription desc=subsets[i].normalMap.GetLevelDescription(0);
                        subsets[i].data.nWidth=desc.Width;
                        subsets[i].data.nHeight=desc.Height;
                        subsets[i].data.nformat=desc.Format;
                    } else subsets[i].data.nWidth=-1;
                } else {
                    subsets[i].colorMap=null;
                    subsets[i].data.cWidth=-1;
                    subsets[i].data.gWidth=-1;
                    subsets[i].data.nWidth=-1;
                }

                //Get vertex information
                VertexElement[] decl=new VertexElement[7];
                decl[0]=new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0);
                decl[1]=new VertexElement(0, 12, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Tangent, 0);
                decl[2]=new VertexElement(0, 24, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.BiNormal, 0);
                decl[3]=new VertexElement(0, 36, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0);
                decl[4]=new VertexElement(0, 48, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0);
                decl[5]=new VertexElement(0, 56, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0);
                decl[6]=VertexElement.VertexDeclarationEnd;
                subsets[i].vDecl=new VertexDeclaration(device, decl);

                if(subsets[i].info.containsTangentBinormal) {
                    Mesh m=new Mesh(subsets[i].info.iCount/3, subsets[i].info.vCount, MeshFlags.SystemMemory, decl, device);

                    subsets[i].vBuffer=new VertexBuffer(typeof(ConvertedVertex), subsets[i].info.vCount, device, Usage.WriteOnly, VertexFormats.None, Pool.Managed);
                    //ConvertedVertex[] cv=(ConvertedVertex[])subsets[i].vBuffer.Lock(0, LockFlags.None);
                    ConvertedVertex[] cv=(ConvertedVertex[])m.LockVertexBuffer(typeof(ConvertedVertex), LockFlags.None, subsets[i].info.vCount);
                    fixed(ConvertedVertex* cvPtr = cv) {
                        GetVerticies(i, cvPtr);
                    }
                    m.UnlockVertexBuffer();
                    //subsets[i].vBuffer.Unlock();

                    //Indicies
                    subsets[i].iBuffer=new IndexBuffer(typeof(ushort), subsets[i].info.iCount, device, Usage.WriteOnly, Pool.Managed);
                    //ushort[] indicies=(ushort[])subsets[i].iBuffer.Lock(0, LockFlags.None);
                    ushort[] indicies=(ushort[])m.LockIndexBuffer(typeof(ushort), LockFlags.None, subsets[i].info.iCount);
                    fixed(ushort* iPtr = indicies) {
                        GetIndicies(i, iPtr);
                    }
                    //subsets[i].iBuffer.Unlock();
                    m.UnlockIndexBuffer();
                    subsets[i].numTris=subsets[i].info.iCount/3;

                    int[] adj=new int[subsets[i].info.iCount];
                    m.GenerateAdjacency(0.01f, adj);
                    m.ComputeTangent(0, 0, 0, 1, adj);

                    //m.ComputeTangentFrame(TangentOptions.CalculateNormals|TangentOptions.GenerateInPlace);
//.........这里部分代码省略.........
开发者ID:BioBrainX,项目名称:fomm,代码行数:101,代码来源:NifFile.cs

示例11: ColoredSpherePartial


//.........这里部分代码省略.........
            if (double.IsNaN(camHead)) camHead = 0;
            camHead = MathEngine.RadiansToDegrees(camHead);
            double startLon = -camHead - 180 + (lonSpan / 2);

            Mesh mesh = new Mesh(numFaces, numVertices, MeshFlags.Managed, CustomVertex.PositionColored.Format, device);

            // Get the original sphere's vertex buffer.
            int[] ranks = new int[1];
            ranks[0] = mesh.NumberVertices;
            System.Array arr = mesh.VertexBuffer.Lock(0, typeof(CustomVertex.PositionColored), LockFlags.None, ranks);

            // Set the vertex buffer
            int vertIndex = 0;
            CustomVertex.PositionColored pnt;
            Vector3 v;

            // bottom fade
            double latitude = startLat - ((endLat - startLat) / 10);
            if (latitude < startLat - 1) latitude = startLat - 1;
            for (int slice = 0; slice <= slices; slice++)
            {
                pnt = new CustomVertex.PositionColored();
                double longitude = startLon - ((float)slice / slices * lonSpan);
                v = MathEngine.SphericalToCartesian(latitude, longitude, radius);
                v.TransformCoordinate(SkyGradientTrans);
                pnt.X = v.X;
                pnt.Y = v.Y;
                pnt.Z = v.Z;
                pnt.Color = System.Drawing.Color.FromArgb(0, 0, 0, 0).ToArgb();
                arr.SetValue(pnt, vertIndex++);
            }
            // stacks and slices
            for (int stack = 1; stack < stacks; stack++)
            {
                //latitude = startLat + ((float)(stack-1)/(stacks-1f)*(float)(endLat - startLat));
                double linear = (float)(stack - 1) / (stacks - 1f);
                double k = 1 - Math.Cos((float)(stack - 1) / (stacks - 1f) * Math.PI / 2);
                latitude = startLat + (k * k * k * (float)(endLat - startLat));
                //double colorFactorZ = (float)(stack-1)/(stacks-1f); 	// coef zenith color
                double colorFactorZ = linear; 				// coef zenith color
                double colorFactorH = 1 - colorFactorZ;			// coef horizon color
                double alphaFactor = 1 - (linear * linear * linear);	// coef alpha transparency
                if (alphaFactor > .8) alphaFactor = .8f;
                for (int slice = 0; slice <= slices; slice++)
                {
                    pnt = new CustomVertex.PositionColored();
                    double longitude = startLon - ((float)slice / slices * lonSpan);
                    v = MathEngine.SphericalToCartesian(latitude, longitude, radius);
                    v.TransformCoordinate(SkyGradientTrans);
                    pnt.X = v.X;
                    pnt.Y = v.Y;
                    pnt.Z = v.Z;
                    pnt.Color = getAtmosphereColor(drawArgs, pnt);
                    arr.SetValue(pnt, vertIndex++);
                }
            }
            // top fade
            latitude = endLat + ((endLat - startLat) / 10);
            for (int slice = 0; slice <= slices; slice++)
            {
                pnt = new CustomVertex.PositionColored();
                double longitude = startLon - ((float)slice / slices * lonSpan);
                v = MathEngine.SphericalToCartesian(latitude, longitude, radius);
                v.TransformCoordinate(SkyGradientTrans);
                pnt.X = v.X;
                pnt.Y = v.Y;
                pnt.Z = v.Z;
                pnt.Color = System.Drawing.Color.FromArgb(0, 0, 0, 0).ToArgb();
                arr.SetValue(pnt, vertIndex++);
            }

            mesh.VertexBuffer.Unlock();
            ranks[0] = indexCount;
            arr = mesh.LockIndexBuffer(typeof(short), LockFlags.None, ranks);
            int i = 0;
            short bottomVertex = 0;
            short topVertex = 0;

            // stacks and slices
            for (short x = 0; x < stacks; x++)
            {
                bottomVertex = (short)((slices + 1) * x);
                topVertex = (short)(bottomVertex + slices + 1);
                for (int y = 0; y < slices; y++)
                {
                    arr.SetValue(bottomVertex, i++);
                    arr.SetValue((short)(topVertex + 1), i++);
                    arr.SetValue(topVertex, i++);
                    arr.SetValue(bottomVertex, i++);
                    arr.SetValue((short)(bottomVertex + 1), i++);
                    arr.SetValue((short)(topVertex + 1), i++);
                    bottomVertex++;
                    topVertex++;
                }
            }

            mesh.IndexBuffer.SetData(arr, 0, LockFlags.None);

            return mesh;
        }
开发者ID:jpespartero,项目名称:WorldWind,代码行数:101,代码来源:World.cs

示例12: CalculateTangents

        /// <summary>
        /// Static method to calculate tangents along with the handedness of the tangents.
        /// </summary>
        /// <param name="model">Model to calculate the tangents on.</param>
        public static void CalculateTangents(Mesh model)
        {
            // Get a copy of the buffers.
            GraphicsStream ib = model.LockIndexBuffer(LockFlags.None);
            GraphicsStream vb = model.LockVertexBuffer(LockFlags.None);

            // List of the final vertex list.
            List<Vertex> final = new List<Vertex>();

            // Temperary lists to store vectors in.
            List<Vector3> tan1 = new List<Vector3>(model.NumberVertices);
            List<Vector3> tan2 = new List<Vector3>(model.NumberVertices);

            // Loop through and copy the vertex list from the vertex buffer
            // and to also add empty values to tan1 and tan2.
            for (int i = 0; i < model.NumberVertices; i++)
            {
                final.Add((Vertex)vb.Read(typeof(Vertex)));
                tan1.Add(new Vector3());
                tan2.Add(new Vector3());
            }

            // Various variables used in the calculation.
            int i1, i2, i3;
            Vector3 v1, v2, v3;
            Vector2 w1, w2, w3;

            float x1, x2, y1, y2, z1, z2;
            float s1, s2, t1, t2, r;

            // Loop through and calculate the tangent information.
            for (int i = 0; i < model.NumberFaces; i++)
            {
                i1 = (int)ib.Read(typeof(int));
                i2 = (int)ib.Read(typeof(int));
                i3 = (int)ib.Read(typeof(int));

                // Get the vertex values for the 3 vertices of a face.
                Vertex vertex1 = final[i1];
                Vertex vertex2 = final[i2];
                Vertex vertex3 = final[i3];

                // Get the positions.
                v1 = vertex1.Position;
                v2 = vertex2.Position;
                v3 = vertex3.Position;

                // Get the texture coordinates.
                w1 = vertex1.TexCoord;
                w2 = vertex2.TexCoord;
                w3 = vertex3.TexCoord;

                x1 = v2.X - v1.X;
                x2 = v3.X - v1.X;
                y1 = v2.Y - v1.Y;
                y2 = v3.Y - v1.Y;
                z1 = v2.Z - v1.Z;
                z2 = v3.Z - v1.Z;

                s1 = w2.X - w1.X;
                s2 = w3.X - w1.X;
                t1 = w2.Y - w1.Y;
                t2 = w3.Y - w1.Y;

                r = 1.0F / (s1 * t2 - s2 * t1);

                // Calculate the direction of the vector
                Vector3 sdir = new Vector3((t2 * x1 - t1 * x2) * r,
                                                    (t2 * y1 - t1 * y2) * r,
                                                    (t2 * z1 - t1 * z2) * r);
                // Calculate the direction of the uv
                Vector3 tdir = new Vector3((s1 * x2 - s2 * x1) * r,
                                                    (s1 * y2 - s2 * y1) * r,
                                                    (s1 * z2 - s2 * z1) * r);

                Vector3 temp1 = tan1[i1];
                Vector3 temp2 = tan1[i2];
                Vector3 temp3 = tan1[i3];
                Vector3 temp4 = tan2[i1];
                Vector3 temp5 = tan2[i2];
                Vector3 temp6 = tan2[i3];

                tan1[i1] = temp1 + sdir;
                tan1[i2] = temp2 + sdir;
                tan1[i3] = temp3 + sdir;

                tan2[i1] = temp4 + tdir;
                tan2[i2] = temp5 + tdir;
                tan2[i3] = temp6 + tdir;
            }

            for (int i = 0; i < model.NumberVertices; i++)
            {
                Vertex tempVertex = final[i];

                Vector3 n = tempVertex.Normal;
//.........这里部分代码省略.........
开发者ID:TheKeg,项目名称:Polyviewer,代码行数:101,代码来源:TangentBuilder.cs

示例13: CreateFrame

        private AnimationFrame CreateFrame(remBone frame, remParser parser, HashSet<string> extractFrames, remMesh mesh, Device device, Matrix combinedParent, List<AnimationFrame> meshFrames)
        {
            AnimationFrame animationFrame = new AnimationFrame();
            animationFrame.Name = frame.name.ToString();
            animationFrame.TransformationMatrix = frame.matrix;
            animationFrame.OriginalTransform = animationFrame.TransformationMatrix;
            animationFrame.CombinedTransform = combinedParent * animationFrame.TransformationMatrix;

            if (frame.name == mesh.frame)
            {
                ExtendedMaterial[] materials = new ExtendedMaterial[mesh.numMats];

                List<List<remVertex>> submeshVertLists = new List<List<remVertex>>(mesh.numMats);
                List<List<ushort>> submeshFaceLists = new List<List<ushort>>(mesh.numMats);
                List<int[]> submeshVertIndices = new List<int[]>(mesh.numMats);
                SplitMesh(mesh, submeshVertLists, submeshFaceLists, submeshVertIndices);

                remSkin boneList = rem.FindSkin(mesh.name, parser.SKIC);
                bool skinned = boneList != null;
                int numBones = skinned ? boneList.Count : 0;
                List<string> boneNamesList = new List<string>(numBones);
                List<Matrix> boneOffsetsList = new List<Matrix>(numBones);
                for (int boneIdx = 0; boneIdx < numBones; boneIdx++)
                {
                    boneNamesList.Add(boneList[boneIdx].bone.ToString());
                    boneOffsetsList.Add(boneList[boneIdx].matrix);
                }
                List<string> boneFrameParentNames = new List<string>(numBones);
                List<Matrix> boneFrameParentMatrices = new List<Matrix>(numBones);
                for (int boneIdx = 0; boneIdx < numBones; boneIdx++)
                {
                    remBone boneFrame = rem.FindFrame(boneList[boneIdx].bone, parser.BONC.rootFrame);
                    if (boneFrame == null)
                    {
                        continue;
                    }
                    remBone boneFrameParent = boneFrame.Parent;
                    if (!boneNamesList.Contains(boneFrameParent.name) && !boneFrameParentNames.Contains(boneFrameParent.name))
                    {
                        boneFrameParentNames.Add(boneFrameParent.name);
                        Matrix incompleteMeshFrameCorrection = Matrix.Invert(frame.matrix);
                        boneFrameParentMatrices.Add(incompleteMeshFrameCorrection * Matrix.Invert(boneFrame.matrix) * boneList[boneIdx].matrix);
                    }
                }
                boneNamesList.AddRange(boneFrameParentNames);
                string[] boneNames = boneNamesList.ToArray();
                boneOffsetsList.AddRange(boneFrameParentMatrices);
                Matrix[] boneOffsets = boneOffsetsList.ToArray();

                AnimationMeshContainer[] meshContainers = new AnimationMeshContainer[submeshFaceLists.Count];
                Vector3 min = new Vector3(Single.MaxValue);
                Vector3 max = new Vector3(Single.MinValue);
                for (int i = 0; i < submeshFaceLists.Count; i++)
                {
                    List<ushort> faceList = submeshFaceLists[i];
                    List<remVertex> vertexList = submeshVertLists[i];

                    Mesh animationMesh = new Mesh(device, faceList.Count, vertexList.Count, MeshFlags.Managed, PositionBlendWeightsIndexedNormalTexturedColoured.Format);

                    using (DataStream indexStream = animationMesh.LockIndexBuffer(LockFlags.None))
                    {
                        for (int j = 0; j < faceList.Count; j++)
                        {
                            indexStream.Write(faceList[j]);
                        }
                        animationMesh.UnlockIndexBuffer();
                    }

                    byte[][] vertexBoneIndices = null;
                    float[][] vertexWeights = ConvertVertexWeights(vertexList, submeshVertIndices[i], boneList, out vertexBoneIndices);
                    FillVertexBuffer(animationMesh, vertexList, vertexWeights, vertexBoneIndices, -1);

                    var normalLines = new PositionBlendWeightsIndexedColored[vertexList.Count * 2];
                    for (int j = 0; j < vertexList.Count; j++)
                    {
                        remVertex vertex = vertexList[j];
                        Vector3 position = vertex.Position;
                        Vector3 normal = vertex.Normal;
                        float[] boneWeights = vertexWeights[j];

                        normalLines[j * 2] = new PositionBlendWeightsIndexedColored(position, boneWeights, vertexBoneIndices[j], Color.Coral.ToArgb());
                        normalLines[(j * 2) + 1] = new PositionBlendWeightsIndexedColored(position + normal, boneWeights, vertexBoneIndices[j], Color.Blue.ToArgb());

            #if !DONT_MIRROR
                        position.Z *= -1f;
            #endif
                        min = Vector3.Minimize(min, position);
                        max = Vector3.Maximize(max, position);
                    }

                    AnimationMeshContainer meshContainer = new AnimationMeshContainer();
                    meshContainer.Name = animationFrame.Name;
                    meshContainer.MeshData = new MeshData(animationMesh);
                    meshContainer.NormalLines = normalLines;
                    meshContainer.BoneNames = boneNames;
                    meshContainer.BoneOffsets = boneOffsets;
                    meshContainers[i] = meshContainer;

                    remMaterial mat = rem.FindMaterial(mesh.materials[i], parser.MATC);
                    if (mat != null)
//.........这里部分代码省略.........
开发者ID:hejob,项目名称:SB3Utility,代码行数:101,代码来源:RenderObjectREM.cs

示例14: BuildGridGeometry

        void BuildGridGeometry()
        {
            Vector3[] globalverts, gridverts;
            int[] globalindices, gridindices, gridindices2;

            float dx = 10.0f;
            float dz = 10.0f;

            // Generate global grid
            GenTriGrid(inputImageHeight, inputImageWidth, dx, dz, new Vector3(0.0f, -1000f, 0f), out globalverts, out globalindices);

            // Number of sub-grids
            int nGridsY = GetGoodAverage(inputImageHeight);
            int nGridsX = GetGoodAverage(inputImageWidth);

            // Subgrid size
            int GridW = inputImageWidth / nGridsX;
            int GridD = inputImageHeight / nGridsY;

            int gridNumVerts = (GridW+1) * (GridD+1);
            int gridNumTris = (GridD ) * (GridW ) * 2;

            // Generate subgrid indices
            GenTriGrid(GridD+1, GridW+1, dx, dz, new Vector3(0.0f, -5000f, 0f), out gridverts, out gridindices);
            GenTriGrid(GridD, GridW, dx, dz, new Vector3(0.0f, -5000f, 0f), out gridverts, out gridindices2);

            // Define some often used variables
            bool overflowX = false, overflowY = false;
            float w = (GridW*nGridsX) * dx;
            float d = (GridD * nGridsY) * dz;
            Vector3 normal = new Vector3(0f, 1f, 0f);
            Mesh mesh;
            VertexPositionNormalTextured[] vertexData = new VertexPositionNormalTextured[gridNumVerts];
            int subgridX, subgridY, globalIndex, gridIndex;

            // foreach subgrid
            for (int gridX = 0; gridX < nGridsX; gridX++)
            {
                for (int gridY = 0; gridY < nGridsY; gridY++)
                {
                    overflowY = false;
                    overflowX = false;
                    mesh = new Mesh(Renderer.Instance.device, gridNumTris, gridNumVerts, MeshFlags.Use32Bit, VertexPositionNormalTextured.Format);

                    // Check for overflow
                    if ((gridX+1) * (GridW + 1) > inputImageWidth)
                        overflowX = true;
                    else if ((gridY+1) * (GridD + 1) > inputImageHeight)
                        overflowY = true;
                    if (overflowY || overflowX)
                    {
                    }
                    else
                    {
                        for (int subD = 0; subD < GridD + 1; ++subD)
                        {
                            for (int subW = 0; subW < GridW + 1; ++subW)
                            {
                                subgridX = gridX * GridW + subW;
                                subgridY = gridY * GridD + subD;
                                globalIndex = (subgridY * inputImageHeight) + subgridX;
                                gridIndex = (subD * (GridD + 1)) + subW;

                                vertexData[gridIndex].Position = globalverts[globalIndex];
                                //vertexData[gridIndex].Y += GetHeightFromImage(subgridY, subgridX) * scale;
                                vertexData[gridIndex].Position.Y += SampleHeightMap3x3(subgridY, subgridX) * scale;
                                vertexData[gridIndex].Normal = normal;
                                vertexData[gridIndex].TextureCoordinate = new Vector2((vertexData[gridIndex].Position.X + (0.5f * w)) / w, (vertexData[gridIndex].Position.Z - (0.5f * d)) / -d);
                            }
                        }

                        DataStream gs = mesh.LockVertexBuffer(LockFlags.None);
                        gs.WriteRange<VertexPositionNormalTextured>(vertexData);
                        gs.Seek(0, SeekOrigin.Begin);
                        // Todo: Fix AABB and frustrum culling
                        Vector3 min, max;
                        //Geometry.ComputeBoundingBox(gs, gridNumVerts, VertexPositionNormalTextured.Format, out min, out max);
                        mesh.UnlockVertexBuffer();

                        //int[] meshIndices = new int[gridNumTris * 3];
                        DataStream ds = mesh.LockAttributeBuffer(LockFlags.None);
                        for (int i = 0; i < gridNumTris; ++i)
                        {
                            ds.Write<int>(0);
                        }
                        mesh.UnlockAttributeBuffer();

                        //meshIndices = ;
                        gs = mesh.LockIndexBuffer(LockFlags.None);
                        gs.WriteRange<int>(gridindices);
                        mesh.UnlockIndexBuffer();

                        //gs = mesh.LockAttributeBuffer(LockFlags.None);
                        //gs.Write(meshAttr);

                        mesh.ComputeNormals();
                        int[] adj = new int[mesh.FaceCount * 3];
                        mesh.GenerateAdjacency(float.Epsilon);
                        //mesh.OptimizeInPlace(MeshFlags.OptimizeAttributeSort | MeshFlags.OptimizeVertexCache | MeshFlags.OptimizeCompact, adj);
                        Mesh newmesh = mesh.Clone(Renderer.Instance.device, MeshFlags.Managed, VertexPosTexNormalTanBitan.Elements);
//.........这里部分代码省略.........
开发者ID:maesse,项目名称:CubeHags,代码行数:101,代码来源:HeightMap.cs

示例15: UpdateResource

        public void UpdateResource(IPluginOut ForPin, int OnDevice)
        {
            if (ForPin == this.FPinOutMesh)
            {

                bool update = this.FMeshes.ContainsKey(OnDevice);
                if (this.FInvalidate)
                {
                    RemoveResource(OnDevice);
                }

                if (!update)
                {
                    this.FInvalidate = true;
                }

                if (this.FInvalidate)
                {

                    Device dev = Device.FromPointer(new IntPtr(OnDevice));

                    List<Mesh> meshes = new List<Mesh>();
                    //Mesh.

                    for (int i = 0; i < this.FVertexList.Count; i++)
                    {

                        Mesh mesh = new Mesh(dev, this.FIndexList[i].Length / 3, this.FVertexList[i].Length, MeshFlags.Dynamic, VertexNormT2.Format);
                        DataStream vS = mesh.LockVertexBuffer(LockFlags.Discard);
                        DataStream iS = mesh.LockIndexBuffer(LockFlags.Discard);

                        FLogger.Log(LogType.Debug,this.FVertexList[i].Length.ToString());
                        FLogger.Log(LogType.Debug,this.FIndexList[i].Length.ToString());

                        vS.WriteRange(this.FVertexList[i]);
                        iS.WriteRange(this.FIndexList[i]);

                        mesh.UnlockVertexBuffer();
                        mesh.UnlockIndexBuffer();

                        meshes.Add(mesh);

                        FLogger.Log(LogType.Debug,meshes.Count.ToString());
                    }

                    try
                    {

                    Mesh merge = Mesh.Concatenate(dev, meshes.ToArray(), MeshFlags.Use32Bit | MeshFlags.Managed);
                    this.FMeshes.Add(OnDevice, merge);
                    //FLogger.Log(LogType.Debug,meshes.Count.ToString());
                    }
                    catch (Exception ex)
                    {
                    //FLogger.Log(LogType.Error,ex.Message);
                    }

                    foreach (Mesh m in meshes)
                    {
                        m.Dispose();
                    }

                    dev.Dispose();

                    this.FInvalidate = false;
                }
            }
        }
开发者ID:hrovac,项目名称:Addons,代码行数:68,代码来源:MeshJoin.cs


注:本文中的Mesh.LockIndexBuffer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。