/// <summary> /// 생성 이벤트 처리 Mesh의 기본 형태 결정 /// </summary> /// <param name="sender">VertexBuffer</param> /// <param name="e"></param> public virtual void OnCreateVertexBuffer(object sender, EventArgs e) { VertexBuffer vb = (VertexBuffer)sender; GraphicsStream stm = vb.Lock(0, 0, 0); CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[4]; verts[0].X = 0.5f; verts[0].Y = -0.5f; verts[0].Z = 0; verts[0].Nx = 0; verts[0].Ny = 0; verts[0].Nz = -1; verts[0].Tu = Scale.X; verts[0].Tv = Scale.Y; verts[1].X = -0.5f; verts[1].Y = -0.5f; verts[1].Z = 0; verts[1].Nx = 0; verts[1].Ny = 0; verts[1].Nz = -1; verts[1].Tu = 0; verts[1].Tv = Scale.Y; verts[2].X = 0.5f; verts[2].Y = 0.5f; verts[2].Z = 0; verts[2].Nx = 0; verts[2].Ny = 0; verts[2].Nz = -1; verts[2].Tu = Scale.X; verts[2].Tv = 0; verts[3].X = -0.5f; verts[3].Y = 0.5f; verts[3].Z = 0; verts[3].Nx = 0; verts[3].Ny = 0; verts[3].Nz = -1; verts[3].Tu = 0; verts[3].Tv = 0; stm.Write(verts); vb.Unlock(); }
private void loadGeometry() { int vertexCount = vertice.GetLength(0); CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[vertexCount]; for (int i = 0; i < vertexCount; ++i) { verts[i].X = vertice[i, 0]; verts[i].Y = vertice[i, 1]; verts[i].Z = vertice[i, 2]; verts[i].Nx = vertice[i, 3]; verts[i].Ny = vertice[i, 4]; verts[i].Nz = vertice[i, 5]; verts[i].Tu = vertice[i, 6]; verts[i].Tv = vertice[i, 7]; } vb = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), vertexCount, graphics.Device, Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Managed); vb.SetData(verts, 0, 0); int triangleCount = triangles.GetLength(0); short[] indice = new short[triangleCount * 3]; for (int i = 0; i < triangleCount; ++i) { indice[i * 3 + 0] = triangles[i, 0]; indice[i * 3 + 1] = triangles[i, 1]; indice[i * 3 + 2] = triangles[i, 2]; } ib = new IndexBuffer(typeof(short), triangleCount * 3, graphics.Device, Usage.WriteOnly, Pool.Managed); ib.SetData(indice, 0, 0); }
public void InitDevice(Device device, bool isReset) { float radius = 1000; /* Adjust this to get more or less perspective distorsion. */ float azimuth, azimuth_step; float elevation, elevation_step; int k, j, c; NumOfVertices = (hres + 1) * (vres + 1); NumOfFaces = (2 * vres - 1) * hres; azimuth_step = 2.0f * (float)Math.PI / hres; elevation_step = half_sphere * (float)Math.PI / 2.0f / vres; CustomVertex.PositionNormalTextured[] vtx = new CustomVertex.PositionNormalTextured[NumOfVertices]; c = 0; for (k = 0, azimuth = 0; k <= hres; k++, azimuth += azimuth_step) { for (j = 0, elevation = (float)Math.PI / 2.0f; j <= vres; j++, elevation -= elevation_step) { vtx[c].Position = new Microsoft.DirectX.Vector3(radius * (float)Math.Cos(elevation) * (float)Math.Sin(azimuth), radius * (float)Math.Sin(elevation) + 50, radius * (float)Math.Cos(elevation) * (float)Math.Cos(azimuth)); vtx[c].Tu = (float)k / (float)hres; vtx[c].Tv = (float)j / (float)vres * img_pct; c++; } } vertices = new VertexBuffer( typeof(CustomVertex.PositionNormalTextured), // Quel type de sommets NumOfVertices, // Combien device, // Le device 0, // Utilisation par défaut CustomVertex.PositionNormalTextured.Format, // Format de sommets Pool.Default); // Pooling par défaut vertices.SetData(vtx, 0, 0); int[] Indices = new int[3 * NumOfFaces]; c = 0; for (k = 0; k < hres; k++) { Indices[c++] = vres + 2 + (vres + 1) * k; Indices[c++] = 1 + (vres + 1) * k; Indices[c++] = 0 + (vres + 1) * k; for (j = 1; j < vres; j++) { Indices[c++] = vres + 2 + (vres + 1) * k + j; Indices[c++] = 1 + (vres + 1) * k + j; Indices[c++] = 0 + (vres + 1) * k + j; Indices[c++] = vres + 1 + (vres + 1) * k + j; Indices[c++] = vres + 2 + (vres + 1) * k + j; Indices[c++] = 0 + (vres + 1) * k + j; } } indices = new IndexBuffer(Indices[0].GetType(), 3 * NumOfFaces, device, 0, Pool.Default); indices.SetData(Indices, 0, 0); Image.InitDevice(device, isReset); }
/// <summary> /// 버퍼 재정의 >> 형태가 다르므로 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public override void OnCreateVertexBuffer(object sender, EventArgs e) { VertexBuffer vb = (VertexBuffer)sender; GraphicsStream stm = vb.Lock(0, 0, 0); CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[4]; verts[0].X = 1; verts[0].Y =0; verts[0].Z = 0f; verts[0].Nx = 0; verts[0].Ny = 0; verts[0].Nz = -1; verts[0].Tu = Scale.X; verts[0].Tv = Scale.Y; verts[1].X = 0; verts[1].Y = 0; verts[1].Z = 0; verts[1].Nx = 0; verts[1].Ny = 0; verts[1].Nz = -1; verts[1].Tu = 0; verts[1].Tv = Scale.Y; verts[2].X = 1; verts[2].Y = 0; verts[2].Z = 1; verts[2].Nx = 0; verts[2].Ny = 0; verts[2].Nz = -1; verts[2].Tu = Scale.X; verts[2].Tv = 0; verts[3].X = 0; verts[3].Y = 0; verts[3].Z = 1; verts[3].Nx = 0; verts[3].Ny = 0; verts[3].Nz = -1; verts[3].Tu = 0; verts[3].Tv = 0; stm.Write(verts); vb.Unlock(); }
private Mesh CreateMesh(aiMesh aiMesh, out Vector3 min, out Vector3 max) { var numFaces = (int)aiMesh.mNumFaces; var numVertices = (int)aiMesh.mNumVertices; var dxMesh = new Mesh(numFaces, numVertices, MeshFlags.Managed | MeshFlags.Use32Bit, CustomVertex.PositionNormalTextured.Format, device); var aiPositions = aiMesh.mVertices; var aiNormals = aiMesh.mNormals; var aiTextureCoordsAll = aiMesh.mTextureCoords; var aiTextureCoords = (aiTextureCoordsAll != null) ? aiTextureCoordsAll[0] : null; var dxVertices = new CustomVertex.PositionNormalTextured[numVertices]; for (int i = 0; i < numVertices; ++i) { dxVertices[i].Position = aiPositions[i].ToVector3(); if (aiNormals != null) { dxVertices[i].Normal = aiNormals[i].ToVector3(); } if (aiTextureCoords != null) { var uv = aiTextureCoords[i]; dxVertices[i].Tu = uv.x; dxVertices[i].Tv = uv.y; } } dxMesh.VertexBuffer.SetData(dxVertices, 0, LockFlags.None); var aiFaces = aiMesh.mFaces; var dxIndices = new uint[numFaces * 3]; for (int i = 0; i < numFaces; ++i) { var aiFace = aiFaces[i]; var aiIndices = aiFace.mIndices; for (int j = 0; j < 3; ++j) { dxIndices[i * 3 + j] = aiIndices[j]; } } dxMesh.IndexBuffer.SetData(dxIndices, 0, LockFlags.None); var dxAttributes = dxMesh.LockAttributeBufferArray(LockFlags.None); // TODO: Set face material index for attributes dxMesh.UnlockAttributeBuffer(dxAttributes); var adjacency = new int[numFaces * 3]; dxMesh.GenerateAdjacency(0.0f, adjacency); dxMesh.OptimizeInPlace(MeshFlags.OptimizeAttributeSort, adjacency); Geometry.ComputeBoundingBox(dxVertices, CustomVertex.PositionNormalTextured.StrideSize, out min, out max); return(dxMesh); }
/// <summary> /// Overridden. See <see cref="P3Node.FillVertexBuffer">P3Node.FillVertexBuffer</see>. /// </summary> protected override void FillVertexBuffer(VertexBuffer vb) { GraphicsStream stm = vb.Lock(0, 0, 0); CustomVertex.PositionNormalTextured[] texVerts = new CustomVertex.PositionNormalTextured[VERTEX_COUNT]; P3Util.CreateTexturedRectangle(texVerts, 0, Bounds); stm.Write(texVerts); vb.Unlock(); }
public CustomVertex.PositionNormalTextured[] ExportDirectX(int Col) { int count = RawFaces.Count() * 3; CustomVertex.PositionNormalTextured[] t = new CustomVertex.PositionNormalTextured[count]; int sel = 0; bool hasUVs = true; if (UVSets == null || UVSets.Count == 0) { hasUVs = false; } if (hasUVs) { sel = UVSets[0].U.Length - 1; } for (int i = 0; i < RawFaces.Count(); i++) { CustomVertex.PositionNormalTextured t2 = new CustomVertex.PositionNormalTextured(); t2.Normal = getNormal(new Vector3(Vertices[RawFaces[i].e0].x, Vertices[RawFaces[i].e0].y, Vertices[RawFaces[i].e0].z), new Vector3(Vertices[RawFaces[i].e1].x, Vertices[RawFaces[i].e1].y, Vertices[RawFaces[i].e1].z), new Vector3(Vertices[RawFaces[i].e2].x, Vertices[RawFaces[i].e2].y, Vertices[RawFaces[i].e2].z)); t2.X = Vertices[RawFaces[i].e0].x; t2.Y = Vertices[RawFaces[i].e0].y; t2.Z = Vertices[RawFaces[i].e0].z; if (hasUVs) { t2.Tu = UVSets[RawFaces[i].e0].U[sel]; t2.Tv = UVSets[RawFaces[i].e0].V[sel]; } t[i * 3] = t2; t2.X = Vertices[RawFaces[i].e1].x; t2.Y = Vertices[RawFaces[i].e1].y; t2.Z = Vertices[RawFaces[i].e1].z; if (hasUVs) { t2.Tu = UVSets[RawFaces[i].e1].U[sel]; t2.Tv = UVSets[RawFaces[i].e1].V[sel]; } t[i * 3 + 1] = t2; t2.X = Vertices[RawFaces[i].e2].x; t2.Y = Vertices[RawFaces[i].e2].y; t2.Z = Vertices[RawFaces[i].e2].z; if (hasUVs) { t2.Tu = UVSets[RawFaces[i].e2].U[sel]; t2.Tv = UVSets[RawFaces[i].e2].V[sel]; } t[i * 3 + 2] = t2; } return(t); }
public OneTriangle(Device device, CallOfCS cocs, CustomVertex.PositionNormalTextured first, CustomVertex.PositionNormalTextured second, CustomVertex.PositionNormalTextured third) : base(device,cocs,0,0,0) { verts = new CustomVertex.PositionNormalTextured[3]; verts[0] = first; verts[1] = second; verts[2] = third; this.center = new Vector3((first.X+second.X+third.X)/3,(first.Y+second.Y+third.Y)/3,(first.Z+second.Z+third.Z)/3); vBuff = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 3, device, Usage.None, CustomVertex.PositionNormalTextured.Format, Pool.Managed); vBuff.SetData(verts,0,LockFlags.None); this.count = 1; this.type = PrimitiveType.TriangleList; }
public Cube(Device device, CallOfCS cocs, short posX, short posZ) : base(device,cocs,posX,posZ,7) { this.center = new Vector3((posX + 0.5f) * size_of_one_rectangle, size_of_one_rectangle * 0.7f, (posZ + 0.5f) * size_of_one_rectangle); this.rotSpeed = constSpeed; lastMove = System.Environment.TickCount; triangles = new ArrayList(); //Totally describe the 3D cube using three dimensional points this.verts = new CustomVertex.PositionNormalTextured[24]; // Front face x y z nx ny nz tu tv verts[0] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); verts[1] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); verts[2] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); verts[3] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); // Right face verts[4] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); verts[5] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); verts[6] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); verts[7] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); // Back face verts[8] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f); verts[9] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f); verts[10] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); verts[11] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); // Left face verts[12] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); verts[13] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); verts[14] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f); verts[15] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); // Top face verts[16] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); verts[17] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); verts[18] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); verts[19] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); // Bottom face verts[20] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f); verts[21] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f); verts[22] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f); verts[23] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f); for(short i = 0; i < 6; i++) { triangles.Add(new OneTriangle(device,cocs,verts[(i*4)],verts[(i*4 + 1)],verts[(i*4 + 2)]) ); triangles.Add(new OneTriangle(device,cocs,verts[(i*4)],verts[(i*4 + 3)],verts[(i*4 + 1)]) ); } this.useTriangles = true; this.inited = true; }
/// <summary> /// Creates a texture from a specified filename (if specified). Creates a plane /// mesh (DirectX mesh object). Mesh size is the texture size. /// </summary> /// <param name="canvas">A GLCore Canvas object.</param> public override void Initialize(Canvas canvas) { if (_filename.Length > 0) { _texture = canvas.LoadTexture(_filename, out _texture_width, out _texture_height); } verts = new CustomVertex.PositionNormalTextured[4]; verts[0] = new CustomVertex.PositionNormalTextured(new Vector3(0, _texture_height, 0f), new Vector3(1, 1, 1), 0, 0); verts[1] = new CustomVertex.PositionNormalTextured(new Vector3(0, 0, 0), new Vector3(1, 1, 1), 0, 1); verts[2] = new CustomVertex.PositionNormalTextured(new Vector3(_texture_width, _texture_height, 0), new Vector3(1, 1, 1), 1, 0); verts[3] = new CustomVertex.PositionNormalTextured(new Vector3(_texture_width, 0, 0), new Vector3(1, 1, 1), 1, 1); Geometry.ComputeBoundingBox(verts, CustomVertex.PositionNormalTextured.Format, out min, out max); }
public void draw(Vector3 cameraRotation, Device device) { device.SetTexture(0, particleTexture); device.TextureState[0].AlphaOperation = TextureOperation.Modulate; device.TextureState[0].AlphaArgument0 = TextureArgument.Current; device.TextureState[0].AlphaArgument1 = TextureArgument.Diffuse; device.TextureState[0].AlphaArgument2 = TextureArgument.TextureColor; device.TextureState[0].ColorArgument0 = TextureArgument.Current; device.TextureState[0].ColorArgument1 = TextureArgument.Diffuse; device.TextureState[0].ColorArgument2 = TextureArgument.TextureColor; device.TextureState[0].ColorOperation = TextureOperation.Modulate; Material material = device.Material; Color diffuse = material.Diffuse; material.Diffuse = fade; material.Emissive = Color.White; device.Material = material; foreach (ParticleData particle in particleList) { device.Transform.World = Matrix.RotationYawPitchRoll(cameraRotation.X, cameraRotation.Y, cameraRotation.Z) * Matrix.Translation(particle.location); VertexBuffer buffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 4, device, 0, CustomVertex.PositionNormalTextured.Format, Pool.Default); CustomVertex.PositionNormalTextured[] vertices = (CustomVertex.PositionNormalTextured[])buffer.Lock(0, 0); float particleRadius = particle.size / 2; vertices[0] = new CustomVertex.PositionNormalTextured(new Vector3(-particleRadius, -particleRadius, 0f), new Vector3(0, 1, 0), 0, 1); // bottom right vertices[1] = new CustomVertex.PositionNormalTextured(new Vector3(-particleRadius, particleRadius, 0f), new Vector3(0, 1, 0), 0, 0); // top right vertices[2] = new CustomVertex.PositionNormalTextured(new Vector3(particleRadius, -particleRadius, 0f), new Vector3(0, 1, 0), 1, 1); // bottom left vertices[3] = new CustomVertex.PositionNormalTextured(new Vector3(particleRadius, particleRadius, 0), new Vector3(0, 1, 0), 1, 0); // top left buffer.Unlock(); device.VertexFormat = CustomVertex.PositionNormalTextured.Format; device.SetStreamSource(0, buffer, 0); device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); } }
public override void OnVertexBufferCreate(object sender, EventArgs e) { vBuff = (VertexBuffer) sender; //nejprve si vytvorime hejno bodu na ktere pak budeme odkazovat z ibufferu this.verts = new CustomVertex.PositionNormalTextured[18]; short foo = 0; // top x y z nx ny nz tu tv verts[foo++] = new CustomVertex.PositionNormalTextured( -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); //bottom x y z nx ny nz tu tv verts[foo++] = new CustomVertex.PositionNormalTextured( 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); //left x y z nx ny nz tu tv verts[foo++] = new CustomVertex.PositionNormalTextured( -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); //right x y z nx ny nz tu tv verts[foo++] = new CustomVertex.PositionNormalTextured( 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); //front1 x y z nx ny nz tu tv verts[foo++] = new CustomVertex.PositionNormalTextured( -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); //front2 x y z nx ny nz tu tv verts[foo++] = new CustomVertex.PositionNormalTextured( -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); verts[foo++] = new CustomVertex.PositionNormalTextured( 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); vBuff.SetData(verts,0,LockFlags.None); this.type = PrimitiveType.TriangleList; this.count = verts.Length/3; }
private void OnCreateVbMapTexture(VertexBuffer buffer) { var texturedArray = (CustomVertex.PositionNormalTextured[])buffer.Lock(0, LockFlags.None); var vector = new Vector3(-(Constants.TileSize / 2f), -(Constants.TileSize / 2f), 0f); var vector2 = new Vector3(Constants.TileSize / 2f, -(Constants.TileSize / 2f), 0f); var vector3 = new Vector3(-(Constants.TileSize / 2f), Constants.TileSize / 2f, 0f); var nor = ComputeNormal(vector, vector2, vector3); texturedArray[0] = new CustomVertex.PositionNormalTextured(vector, nor, 0f, 0f); texturedArray[1] = new CustomVertex.PositionNormalTextured(vector2, nor, 1f, 0f); texturedArray[2] = new CustomVertex.PositionNormalTextured(vector3, nor, 0f, 1f); vector = new Vector3(Constants.TileSize / 2f, Constants.TileSize / 2f, 0f); vector2 = new Vector3(-(Constants.TileSize / 2f), Constants.TileSize / 2f, 0f); vector3 = new Vector3(Constants.TileSize / 2f, -(Constants.TileSize / 2f), 0f); nor = ComputeNormal(vector, vector2, vector3); texturedArray[3] = new CustomVertex.PositionNormalTextured(vector, nor, 1f, 1f); texturedArray[4] = new CustomVertex.PositionNormalTextured(vector2, nor, 0f, 1f); texturedArray[5] = new CustomVertex.PositionNormalTextured(vector3, nor, 1f, 0f); buffer.Unlock(); }
private void CrearObjetosEnElEscenario(CustomVertex.PositionNormalTextured[] vertices) { Random random = new Random(); int posicionesTotales = vertices.Length; // Le resto 2 para que no tener en cuenta los bordes del mapa int posicionesASaltear = 1; // Este valor se cambia adentro del for con un random int minSalto = 1; // Valores para usar en el next del random para saltear int maxSalto = 9; for (int i = verticesWidth; i < posicionesTotales; i += posicionesASaltear) { CustomVertex.PositionNormalTextured verticeActual = vertices[i]; TGCVector3 rotation = TGCVector3.Up * random.Next(10); int scale = random.Next(10, 30); TGCVector3 position = MathExtended.Vector3ToTGCVector3(verticeActual.Position); TgcMesh mesh = meshesPlantas[random.Next(meshesPlantas.Count)]; //GameInstance.InstanceObject(new Collectable(GameInstance, "coral", new List<TgcMesh>(new TgcMesh[] { mesh.createMeshInstance("coral") }), position, scale, rotation, Items.EItemID.CORAL_PIECE)); GameInstance.InstanceStaticSceneObject(new Collectable(GameInstance, "coral", new List <TgcMesh>(new TgcMesh[] { mesh.createMeshInstance("coral") }), position, scale, rotation, Items.EItemID.CORAL_PIECE)); posicionesASaltear = random.Next(minSalto, maxSalto); } }
public override void OnVertexBufferCreate(object sender, EventArgs e) { vBuff = (VertexBuffer) sender; // //================= pres iBuff----------------- //nejprve si vytvorime hejno bodu na ktere pak budeme odkazovat z ibufferu this.verts = new CustomVertex.PositionNormalTextured[4]; // back face verts[0] = new CustomVertex.PositionNormalTextured( 1.0f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f); verts[1] = new CustomVertex.PositionNormalTextured( 0.0f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f); verts[2] = new CustomVertex.PositionNormalTextured( 0.0f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); verts[3] = new CustomVertex.PositionNormalTextured( 1.0f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); vBuff.SetData(verts,0,LockFlags.None); //device.SetStreamSource(0,vBuff,0 ); //points are created so we can prepare ibuffer indexy = new short[6];//fixme pevna velikost neni ok short foo = 0; indexy[foo++] = 0; indexy[foo++] = 3; indexy[foo++] = 1; indexy[foo++] = 0; indexy[foo++] = 1; indexy[foo++] = 2; iBuff = new IndexBuffer(typeof(short), indexy.Length, device, 0 /* Usage.Dynamic | Usage.WriteOnly*/, Pool.Managed); iBuff.SetData(indexy,0,LockFlags.None); //device.Indices = iBuff; this.type = PrimitiveType.TriangleList; this.count = indexy.Length/3;//fixme to by nemelo byt natvrdo this.useIBuff = true; //this.iBuff = new IndexBuffer(); //=================konec pres iBuff-------*/ }
public CustomVertex.PositionNormalTextured[] ExportDirectX(int col, int LOD) { int count = Mesh.LODs[LOD].allFaces; CustomVertex.PositionNormalTextured[] t = new CustomVertex.PositionNormalTextured[count * 3]; int n = 0; int c = 0; for (int i = 0; i < count; i++) { CustomVertex.PositionNormalTextured t2 = new CustomVertex.PositionNormalTextured(); t2.Normal = getNormal(new Vector3(Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e0].X, Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e0].Z, Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e0].Y * -1), new Vector3(Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e1].X, Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e1].Z, Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e1].Y * -1), new Vector3(Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e2].X, Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e2].Z, Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e2].Y * -1)); t2.X = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e0].X; t2.Z = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e0].Y * -1; t2.Y = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e0].Z; //t2.Color = col; t[i * 3] = t2; t2.X = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e1].X; t2.Z = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e1].Y * -1; t2.Y = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e1].Z; //t2.Color = col; t[i * 3 + 1] = t2; t2.X = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e2].X; t2.Z = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e2].Y * -1; t2.Y = Mesh.LODs[LOD].points[Mesh.LODs[LOD].sections[n].Faces[c].e2].Z; //t2.Color = col; t[i * 3 + 2] = t2; c++; if (c == Mesh.LODs[LOD].sections[n].count) { c = 0; n++; } } return(t); }
public override void OnVertexBufferCreate(object sender, EventArgs e) { vBuff = (VertexBuffer)sender; this.verts = new CustomVertex.PositionNormalTextured[sizeX * sizeZ * 4]; int foo = 0; for (int i = 0; i < sizeZ; i++) { for (int j = 0; j < sizeX; j++) { verts[foo++] = new CustomVertex.PositionNormalTextured(j * size_of_one_rectangle, 0, i * size_of_one_rectangle, 0, 1, 0, 0, 1); verts[foo++] = new CustomVertex.PositionNormalTextured(j * size_of_one_rectangle, 0, (i + 1) * size_of_one_rectangle, 0, 1, 0, 0, 0); verts[foo++] = new CustomVertex.PositionNormalTextured((j + 1) * size_of_one_rectangle, 0, (i + 1) * size_of_one_rectangle, 0, 1, 0, 1, 0); verts[foo++] = new CustomVertex.PositionNormalTextured((j + 1) * size_of_one_rectangle, 0, i * size_of_one_rectangle, 0, 1, 0, 1, 1); } } vBuff.SetData(verts, 0, LockFlags.None); indexy = new short[sizeX * sizeZ * 6]; foo = 0; for (short i = 0; i < sizeX; i++) { for (short j = 0; j < sizeZ; j++) { indexy[foo++] = (short)(i * sizeZ * 4 + j * 4); indexy[foo++] = (short)(i * sizeZ * 4 + j * 4 + 2); indexy[foo++] = (short)(i * sizeZ * 4 + j * 4 + 3); indexy[foo++] = (short)(i * sizeZ * 4 + j * 4); indexy[foo++] = (short)(i * sizeZ * 4 + j * 4 + 1); indexy[foo++] = (short)(i * sizeZ * 4 + j * 4 + 2); } } iBuff = new IndexBuffer(typeof(short), indexy.Length, device, 0, Pool.Managed); iBuff.SetData(indexy, 0, LockFlags.None); this.type = PrimitiveType.TriangleList; this.count = Math.Abs(sizeX * sizeZ * 2); this.useIBuff = true; }
public static void CreateSphereTriangles(Vector3 centre, double radius, int numSegments, out CustomVertex.PositionNormalTextured[] points) { int numVerts = numSegments * (numSegments / 2) * 6; points = new CustomVertex.PositionNormalTextured[numVerts]; double theta1, theta2, theta3; Vector3 e, p; if (radius < 0) radius = -radius; if (numSegments < 0) numSegments = -numSegments; int vIdx = 0; for (int j = 0; j < numSegments / 2; j++) { theta1 = j * TWOPI / numSegments - PID2; theta2 = (j + 1) * TWOPI / numSegments - PID2; for (int i = 0; i <= numSegments; i++) { theta3 = i * TWOPI / numSegments; if (i > 0) { e.X = (float)(Math.Cos(theta2) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta2); e.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); // end of T1 points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * (j + 1) / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; e.X = (float)(Math.Cos(theta1) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta1); e.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); // T2 points[vIdx].Normal = points[vIdx - 1].Normal; points[vIdx].Tu = points[vIdx - 1].Tu; points[vIdx].Tv = points[vIdx - 1].Tv; points[vIdx].Position = points[vIdx - 1].Position; vIdx++; points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * j / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; points[vIdx].Normal = points[vIdx - 5].Normal; points[vIdx].Tu = points[vIdx - 5].Tu; points[vIdx].Tv = points[vIdx - 5].Tv; points[vIdx].Position = points[vIdx - 5].Position; vIdx++; // start of T1 if (i < numSegments /*- 1*/) { points[vIdx].Normal = points[vIdx - 2].Normal; points[vIdx].Tu = points[vIdx - 2].Tu; points[vIdx].Tv = points[vIdx - 2].Tv; points[vIdx].Position = points[vIdx - 2].Position; vIdx++; points[vIdx].Normal = points[vIdx - 4].Normal; points[vIdx].Tu = points[vIdx - 4].Tu; points[vIdx].Tv = points[vIdx - 4].Tv; points[vIdx].Position = points[vIdx - 4].Position; vIdx++; } } else { e.X = (float)(Math.Cos(theta1) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta1); e.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * j / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; e.X = (float)(Math.Cos(theta2) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta2); e.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * (j + 1) / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; } } } }
/// <summary> /// Metodo que carga los valores necesarios para inicializar el Oceano. /// </summary> public static void Cargar() { Device d3dDevice = GuiController.Instance.D3dDevice; // Creo la textura de reflexion surf_reflection = new Texture(d3dDevice, GuiController.Instance.Panel3d.Width, GuiController.Instance.Panel3d.Height, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); // Creo la textura de refraccion surf_refraction = new Texture(d3dDevice, GuiController.Instance.Panel3d.Width, GuiController.Instance.Panel3d.Height, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); // Cargo la textura de fresnel (relación entre los campos eléctricos transmitido y reflejado) "fresnel_water_sRGB.bmp" surf_fresnel = TextureLoader.FromFile(d3dDevice, GuiController.Instance.AlumnoEjemplosMediaDir + "Texturas\\fresnel_water_sRGB.bmp"); // Carga el shader del movimiento del oceano //PerlinShader = Utiles.CargarShaderConTechnique("perlin.fx"); Effect PerlinShader = TgcShaders.loadEffect(GuiController.Instance.ExamplesDir + "Shaders\\WorkshopShaders\\Shaders\\shader_agua.fx"); //Effect shader = ShaderUtils.loadEffect(Utiles.ShadersDir(Nombre)); PerlinShader.Technique = "RenderAgua"; // Cargar informacion de vertices: (X,Y,Z) + coord textura _vertices = new CustomVertex.PositionNormalTextured[CANTIDAD_DE_VERTICES]; int i = 0; for (int x = -RADIO; x <= RADIO; x++) { for (int z = -RADIO; z <= RADIO; z++) { _vertices[i++] = new CustomVertex.PositionNormalTextured( new Vector3(x * DISTANCIA_ENTRE_VERTICES,400, z * DISTANCIA_ENTRE_VERTICES), _normal, ((float)(x + RADIO) / ((float)LARGO - 1)), ((float)(z + RADIO) / ((float)LARGO - 1)) ); } }; // Creamos el VertexBuffer _vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), CANTIDAD_DE_VERTICES, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default); // Almacenar información en VertexBuffer _vertexBuffer.SetData(_vertices, 0, LockFlags.None); //Creo el quadTree para este terreno QuadTree.Cargar(_pos.X, _pos.Z, TAMAÑO, GuiController.Instance.D3dDevice); // creo los indices para el IndexBuffer usando un array de int // Son por 3 vertices por triangulo y son 2 triangulos for (int z = 0; z < LARGO - 1; z++) for (int x = 0; x < LARGO - 1; x++) { var lista = new List<int>(); //Primer Triangulo lista.Add(x + z * LARGO); lista.Add(x + 1 + z * LARGO); lista.Add(x + LARGO + 1 + z * LARGO); //Segundo Triangulo lista.Add(x + LARGO + 1 + z * LARGO); lista.Add(x + LARGO + z * LARGO); lista.Add(x + z * LARGO); //Cargo los indices en los nodos del QuadTree QuadTree.AgregarIndices(lista); }; //LOD I for (int z = 0; z < LARGO - 1; z = z + 2) for (int x = 0; x < LARGO - 1; x = x + 2) { var lista = new List<int>(); //Primer Triangulo lista.Add(x + z * LARGO); lista.Add(x + 2 + z * LARGO); lista.Add(x + 2 * LARGO + 2 + z * LARGO); //Segundo Triangulo lista.Add(x + 2 * LARGO + 2 + z * LARGO); lista.Add(x + 2 * LARGO + z * LARGO); lista.Add(x + z * LARGO); //Cargo los indices en los nodos del QuadTree QuadTree.AgregarLODI(lista); }; //LOD II for (int z = 0; z < LARGO - 1; z = z + 4) for (int x = 0; x < LARGO - 1; x = x + 4) { var lista = new List<int>(); //Primer Triangulo lista.Add(x + z * LARGO); lista.Add(x + 4 + z * LARGO); lista.Add(x + 4 * LARGO + 4 + z * LARGO); //Segundo Triangulo lista.Add(x + 4 * LARGO + 4 + z * LARGO); lista.Add(x + 4 * LARGO + z * LARGO); lista.Add(x + z * LARGO); //Cargo los indices en los nodos del QuadTree QuadTree.AgregarLODII(lista); }; // Genera los heightmaps entre los que interpola la superficie, se generan para 2,4 y 8 octavas para poder usar // las diferentes configuraciones cambiando los Modifiers. // 2 ocatavas (ruido fuerte). // perlin 1 textPerlinNoise1_2Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 2, out PerlinNoise1_2Octavas); textPerlinNoise2_2Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 2, out PerlinNoise2_2Octavas); // 4 ocatavas (ruido normal). textPerlinNoise1_4Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 4, out PerlinNoise1_4Octavas); textPerlinNoise2_4Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 4, out PerlinNoise2_4Octavas); // 8 octavas (ruido suave). textPerlinNoise1_8Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 8, out PerlinNoise1_8Octavas); textPerlinNoise2_8Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 8, out PerlinNoise2_8Octavas); // Carga los valores iniciales de la Matriz de Perlin Noise. PerlinNoise1 = PerlinNoise1_8Octavas; PerlinNoise2 = PerlinNoise2_8Octavas; // Carga los valores iniciales de la textura que se usara como Heightmap y Normalmap para la superficie del oceano. textPerlinNoise1 = textPerlinNoise1_8Octavas; textPerlinNoise2 = textPerlinNoise2_8Octavas; // Peso (alpha) para interpolar, usa el InterpoladorVaiven para ir alterandolo. interpoladorPerlinNoiseHeightmaps = new InterpoladorVaiven(); interpoladorPerlinNoiseHeightmaps.Min = 0; interpoladorPerlinNoiseHeightmaps.Max = 1; interpoladorPerlinNoiseHeightmaps.Speed = 0.5f; //guardar el stencil inicial //g_depthstencil = d3dDevice.DepthStencilSurface; }
public static Mesh CreateCylinder(Microsoft.DirectX.Direct3D.Device d3dDevice, float fltBottomRadius, float fltTopRadius, float fltBottom, float fltTop, int iSides) { int j; ArrayList aryStrips = new ArrayList(); ArrayList aryLastStrip = new ArrayList(); ArrayList aryTriangleList1; ArrayList aryTriangleList2; ArrayList aryCombinedList; Vector3[] vVertices = new Vector3[2]; Vector3 vNormal = new Vector3(); CustomVertex.PositionNormalTextured[] aryTopPoly = new CustomVertex.PositionNormalTextured[iSides+1]; CustomVertex.PositionNormalTextured[] aryBottomPoly = new CustomVertex.PositionNormalTextured[iSides+1]; //initialize the strips //for(int iStrip=0; iStrip<3; iStrip++) // aryStrips.Add(new CustomVertex.PositionNormalTextured[2*(iSides+1)]); aryStrips.Add(new CustomVertex.PositionNormalTextured[iSides]); aryStrips.Add(new CustomVertex.PositionNormalTextured[2*(iSides+1)]); aryLastStrip.Add(new CustomVertex.PositionNormalTextured[iSides]); CustomVertex.PositionNormalTextured[] verts0 = (CustomVertex.PositionNormalTextured[]) aryStrips[0]; CustomVertex.PositionNormalTextured[] verts1 = (CustomVertex.PositionNormalTextured[]) aryStrips[1]; CustomVertex.PositionNormalTextured[] verts2 = (CustomVertex.PositionNormalTextured[]) aryLastStrip[0]; vVertices[0] = new Vector3(fltTopRadius, 0, fltTop); vVertices[1] = new Vector3(fltBottomRadius, 0, fltBottom); vNormal = new Vector3(fltBottom-fltTop, 0, fltTopRadius-fltBottomRadius); vNormal.Normalize(); // Work around cylinder to create side and end polygons. Vector3 vVertTmp1, vVertTmp2, vNormTmp; float fltU; for(j=1; j<iSides+1; j++) { float fltAroundAngle = ((float)j/iSides) * 2 * (float) Math.PI; Matrix mR = Matrix3MakeRotationZ(fltAroundAngle); vVertTmp1 = Matrix3MultiplyVector(mR, vVertices[0]); aryTopPoly[j] = new CustomVertex.PositionNormalTextured(vVertTmp1.X, vVertTmp1.Y, vVertTmp1.Z, 0, 0, -1, (float) ((Math.Cos(fltAroundAngle)+1)*(float)0.5), (float) ((Math.Sin(fltAroundAngle)+1)*(float)0.5)); vVertTmp2 = Matrix3MultiplyVector(mR, vVertices[1]); aryBottomPoly[j] = new CustomVertex.PositionNormalTextured(vVertTmp2.X, vVertTmp2.Y, vVertTmp2.Z, 0, 0, 1, (float) ((Math.Cos(fltAroundAngle)+1)*(float)0.5), (float) ((Math.Sin(fltAroundAngle)+1)*(float)0.5)); vNormTmp = Matrix3MultiplyVector(mR, vNormal); fltU = ((float)j/iSides); verts1[j*2] = new CustomVertex.PositionNormalTextured(vVertTmp1.X, vVertTmp1.Y, vVertTmp1.Z, vNormTmp.X, vNormTmp.Y, vNormTmp.Z, fltU, 0); verts1[(j*2)+1] = new CustomVertex.PositionNormalTextured(vVertTmp2.X, vVertTmp2.Y, vVertTmp2.Z, vNormTmp.X, vNormTmp.Y, vNormTmp.Z, fltU, 1); } // CONVERT POLYGONS INTO STRIPS int i = 0; // first vertex j = iSides-1; // last vertex int k = 0; // position in strip while(i <= j) { verts0[k] = aryBottomPoly[i]; verts2[k] = aryTopPoly[i]; k++; if(i != j) { verts0[k] = aryBottomPoly[j]; verts2[k] = aryTopPoly[j]; k++; } i++; j--; } aryTriangleList1 = ConvertTriStripToTriList(aryStrips, true); aryTriangleList2 = ConvertTriStripToTriList(aryLastStrip, false); aryCombinedList = CombineTriangleLists(aryTriangleList1, aryTriangleList2); return CreateMeshFromTriangleList(d3dDevice, aryCombinedList); }
private void MakeLCModels(string SMCFile) { int num = -1; int ID = this.GetIDFromList(); int num2 = ItemList.FindIndex((ItemContainer p) => p.ItemID.Equals(ID)); if (num2 != -1) { int arg_42_0 = ItemList[num2].JobFlag; num = ItemList[num2].Position; } try { List <smcMesh> list = SMCReader.ReadFile(SMCFile); for (int i = 0; i < list.Count <smcMesh>(); i++) { bool flag = (num != 0 || !list[i].FileName.Contains("_hair_000")) && (num != 1 || !list[i].FileName.Contains("_bu_000")) && (num != 3 || !list[i].FileName.Contains("_bd_000")) && (num != 5 || !list[i].FileName.Contains("_hn_000")) && (num != 6 || !list[i].FileName.Contains("_ft_000")); if (flag && LCMeshReader.ReadFile(list[i].FileName)) { tMeshContainer pMesh = LCMeshReader.pMesh; for (int j = 0; j < pMesh.Objects.Count <tMeshObject>(); j++) { int toVert = (int)pMesh.Objects[j].ToVert; uint arg_16B_0 = pMesh.Objects[j].FaceCount; short[] faces = pMesh.Objects[j].GetFaces(); CustomVertex.PositionNormalTextured[] array = new CustomVertex.PositionNormalTextured[toVert]; int num3 = (int)pMesh.Objects[j].FromVert; int k = 0; while ((long)k < (long)((ulong)pMesh.Objects[j].ToVert)) { array[k].Position = new Vector3(pMesh.Vertices[num3].X, pMesh.Vertices[num3].Y, pMesh.Vertices[num3].Z); array[k].Normal = new Vector3(pMesh.Normals[num3].X, pMesh.Normals[num3].Y, pMesh.Normals[num3].Z); try { array[k].Texture = new Vector2(pMesh.UVMaps[0].Coords[num3].U, pMesh.UVMaps[0].Coords[num3].V); } catch { array[k].Texture = new Vector2(0f, 0f); } num3++; k++; } new VertexBuffer(this.device, array.Count <CustomVertex.PositionNormalTextured>() * 32, Usage.None, VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Normal, Pool.Default); Mesh mesh = new Mesh(this.device, faces.Count <short>() / 3, array.Count <CustomVertex.PositionNormalTextured>(), MeshFlags.Managed, VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Normal); DataStream dataStream2; DataStream dataStream = dataStream2 = mesh.VertexBuffer.Lock(0, array.Count <CustomVertex.PositionNormalTextured>() * 32, LockFlags.None); try { dataStream.WriteRange <CustomVertex.PositionNormalTextured>(array); mesh.VertexBuffer.Unlock(); } finally { if (dataStream2 != null) { ((IDisposable)dataStream2).Dispose(); } } DataStream dataStream3; dataStream = (dataStream3 = mesh.IndexBuffer.Lock(0, faces.Count <short>() * 2, LockFlags.None)); try { dataStream.WriteRange <short>(faces); mesh.IndexBuffer.Unlock(); } finally { if (dataStream3 != null) { ((IDisposable)dataStream3).Dispose(); } } if (pMesh.Weights.Count <tMeshJointWeights>() != 0) { string[] array2 = new string[pMesh.Weights.Count <tMeshJointWeights>()]; List <int>[] array3 = new List <int> [pMesh.Weights.Count <tMeshJointWeights>()]; List <float>[] array4 = new List <float> [pMesh.Weights.Count <tMeshJointWeights>()]; for (int l = 0; l < pMesh.Weights.Count <tMeshJointWeights>(); l++) { array2[l] = this.Enc.GetString(pMesh.Weights[l].JointName); array3[l] = new List <int>(); array4[l] = new List <float>(); for (int m = 0; m < pMesh.Weights[l].WeightsMap.Count <tMeshWeightsMap>(); m++) { array3[l].Add(pMesh.Weights[l].WeightsMap[m].Index); array4[l].Add(pMesh.Weights[l].WeightsMap[m].Weight); } } mesh.SkinInfo = new SkinInfo(array.Count <CustomVertex.PositionNormalTextured>(), VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Normal, (int)pMesh.HeaderInfo.JointCount); for (k = 0; k < array3.Count <List <int> >(); k++) { mesh.SkinInfo.SetBoneName(k, array2[k]); mesh.SkinInfo.SetBoneInfluence(k, array3[k].ToArray(), array4[k].ToArray()); } } mesh.GenerateAdjacency(0.5f); mesh.ComputeNormals(); Texture texture = null; string objName = this.Enc.GetString(pMesh.Objects[j].Textures[0].InternalName); int num4 = list[i].Object.FindIndex((smcObject x) => x.Name.Equals(objName)); if (num4 != -1) { texture = this.GetTextureFromFile(list[i].Object[num4].Texture); } this.models.Add(new tMesh(mesh, texture)); } } } } catch { } this.zoom = 4f; }
public void VertexDeclaration() { vb = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 36, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default); vertices = new CustomVertex.PositionNormalTextured[36]; //дно float a = -1.5f; //координата Y первой точки float b = 3.0f; //Длина стороны float c = 0.0f; //смещение параллельной стороны относительно начальной стороны по Oy float d = 5.0f; //смещение параллельной стороны относительно начальной стороны по Ox vertices[0] = new CustomVertex.PositionNormalTextured(0f, a, 0f, 0f, 0f, 1f, 0f, 0f); vertices[1] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, 0f, 0f, 1f, 1f, 0f); vertices[2] = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 0f, 0f, 1f, 0f, 1f); vertices[3] = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 0f, 0f, 1f, 0f, 1f); vertices[4] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, 0f, 0f, 1f, 1f, 0f); vertices[5] = new CustomVertex.PositionNormalTextured(d, c + a + b, 0f, 0f, 0f, 1f, 1f, 1f); //передняя левая vertices[6] = new CustomVertex.PositionNormalTextured(0f, a, 0f, 1f, 0f, 0f, 1f, 0f); vertices[7] = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 1f, 0f, 0f, 0f, 0f); vertices[8] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, 1f, 0f, 0f, 0.5f, 0.5f); //боковая левая float norma1 = (float)Math.Sqrt(25 * c * c + 25 * d * d + d * d * (a + b) * (a + b)); vertices[9] = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 5 * c / norma1, -5 * d / norma1, -d * (a + b) / norma1, 0f, 0f); vertices[10] = new CustomVertex.PositionNormalTextured(d, c + a + b, 0f, 5 * c / norma1, -5 * d / norma1, -d * (a + b) / norma1, 1f, 0f); vertices[11] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, 5 * c / norma1, -5 * d / norma1, -d * (a + b) / norma1, 0.5f, 0.5f); //(5c,-5d,-d(a+b)) //задняя float norma2 = (float)Math.Sqrt(25 * b * b + b * b * d * d); vertices[12] = new CustomVertex.PositionNormalTextured(d, c + a + b, 0, -5 * b / norma2, 0f, -b * d / norma2, 1f, 0f); vertices[13] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, -5 * b / norma2, 0f, -b * d / norma2, 0f, 0f); vertices[14] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, -5 * b / norma2, 0f, -b * d / norma2, 0.5f, 0.5f); //(-5b,0,-bd) //боковая правая float norma3 = (float)Math.Sqrt(25 * c * c + 25 * d * d + a * a * d * d); vertices[15] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, -5 * c / norma3, -5 * d / norma3, a * d / norma3, 0f, 0f); vertices[16] = new CustomVertex.PositionNormalTextured(0f, a, 0f, -5 * c / norma3, -5 * d / norma3, a * d / norma3, 1f, 0f); vertices[17] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, -5 * c / norma3, -5 * d / norma3, a * d / norma3, 0.5f, 0.5f); //(-5c,5d,ad) vb.SetData(vertices, 0, LockFlags.None); for (int i = 18; i < 36; i++) { vertices[i] = new CustomVertex.PositionNormalTextured(vertices[i - 18].X + 1f, vertices[i - 18].Y, vertices[i - 18].Z + 2f, vertices[i - 18].Nx, vertices[i - 18].Ny, vertices[i - 18].Nz, vertices[i - 18].Tu, vertices[i - 18].Tv); } vb.SetData(vertices, 0, LockFlags.None); //индексный буфер показывает, как вершины объединить в треугольники ib = new IndexBuffer(typeof(int), 36, device, Usage.WriteOnly, Pool.Default); indices = new int[36]; //дно - по часовой стрелке indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 3; indices[4] = 4; indices[5] = 5; indices[6] = 6; indices[7] = 7; indices[8] = 8; indices[9] = 9; indices[10] = 10; indices[11] = 11; indices[12] = 12; indices[13] = 13; indices[14] = 14; indices[15] = 15; indices[16] = 16; indices[17] = 17; for (int i = 18; i < 36; i++) { indices[i] = indices[i - 18] + 18; } ib.SetData(indices, 0, LockFlags.None); ib = new IndexBuffer(typeof(int), indices.Length, device, Usage.WriteOnly, Pool.Default); ib.SetData(indices, 0, LockFlags.None); }
private void MakeLCModels(string SMCFile) { System.Collections.Generic.List <float> source1 = new System.Collections.Generic.List <float>(); System.Collections.Generic.List <float> source2 = new System.Collections.Generic.List <float>(); System.Collections.Generic.List <float> source3 = new System.Collections.Generic.List <float>(); System.Collections.Generic.List <float> floatList1 = new System.Collections.Generic.List <float>(); System.Collections.Generic.List <float> floatList2 = new System.Collections.Generic.List <float>(); System.Collections.Generic.List <float> floatList3 = new System.Collections.Generic.List <float>(); _Models = new System.Collections.Generic.List <tMesh>(); try { System.Collections.Generic.List <smcMesh> source4 = SMCReader.ReadFile(SMCFile); for (int index1 = 0; index1 < source4.Count(); ++index1) { if (LCMeshReader.ReadFile(source4[index1].FileName)) { tMeshContainer pMesh = LCMeshReader.pMesh; source1.Add((pMesh.Vertices).Max((p => p.X))); source2.Add((pMesh.Vertices).Max((p => p.Y))); source3.Add((pMesh.Vertices).Max((p => p.Z))); floatList1.Add((pMesh.Vertices).Min((p => p.X))); floatList2.Add((pMesh.Vertices).Min((p => p.Y))); floatList3.Add((pMesh.Vertices).Min(p => p.Z)); for (int index2 = 0; index2 < (pMesh.Objects).Count(); ++index2) { int toVert = (int)pMesh.Objects[index2].ToVert; int faceCount = (int)pMesh.Objects[index2].FaceCount; short[] faces = pMesh.Objects[index2].GetFaces(); CustomVertex.PositionNormalTextured[] data = new CustomVertex.PositionNormalTextured[toVert]; int fromVert = (int)pMesh.Objects[index2].FromVert; for (int index3 = 0; index3 < pMesh.Objects[index2].ToVert; ++index3) { data[index3].Position = new Vector3(pMesh.Vertices[fromVert].X, pMesh.Vertices[fromVert].Y, pMesh.Vertices[fromVert].Z); data[index3].Normal = new Vector3(pMesh.Normals[fromVert].X, pMesh.Normals[fromVert].Y, pMesh.Normals[fromVert].Z); try { data[index3].Texture = new Vector2(pMesh.UVMaps[0].Coords[fromVert].U, pMesh.UVMaps[0].Coords[fromVert].V); } catch { data[index3].Texture = new Vector2(0.0f, 0.0f); } ++fromVert; } VertexBuffer vertexBuffer = new VertexBuffer(_Device, (data).Count() * 32, Usage.None, VertexFormat.PositionNormal | VertexFormat.Texture1, Pool.Default); Mesh mesh = new Mesh(_Device, (faces).Count() / 3, (data).Count(), MeshFlags.Managed, VertexFormat.PositionNormal | VertexFormat.Texture1); DataStream dataStream1; using (dataStream1 = mesh.VertexBuffer.Lock(0, (data).Count() * 32, LockFlags.None)) { dataStream1.WriteRange(data); mesh.VertexBuffer.Unlock(); } DataStream dataStream2; using (dataStream2 = mesh.IndexBuffer.Lock(0, (faces).Count() * 2, LockFlags.None)) { dataStream2.WriteRange(faces); mesh.IndexBuffer.Unlock(); } if ((uint)(pMesh.Weights).Count() > 0U) { string[] strArray = new string[(pMesh.Weights).Count()]; System.Collections.Generic.List <int>[] intListArray = new System.Collections.Generic.List <int> [(pMesh.Weights).Count()]; System.Collections.Generic.List <float>[] floatListArray = new System.Collections.Generic.List <float> [(pMesh.Weights).Count()]; for (int index3 = 0; index3 < (pMesh.Weights).Count(); ++index3) { strArray[index3] = _Enc.GetString(pMesh.Weights[index3].JointName); intListArray[index3] = new System.Collections.Generic.List <int>(); floatListArray[index3] = new System.Collections.Generic.List <float>(); for (int index4 = 0; index4 < (pMesh.Weights[index3].WeightsMap).Count(); ++index4) { intListArray[index3].Add(pMesh.Weights[index3].WeightsMap[index4].Index); floatListArray[index3].Add(pMesh.Weights[index3].WeightsMap[index4].Weight); } } mesh.SkinInfo = new SkinInfo((data).Count(), VertexFormat.PositionNormal | VertexFormat.Texture1, (int)pMesh.HeaderInfo.JointCount); for (int bone = 0; bone < (intListArray).Count(); ++bone) { mesh.SkinInfo.SetBoneName(bone, strArray[bone]); mesh.SkinInfo.SetBoneInfluence(bone, intListArray[bone].ToArray(), floatListArray[bone].ToArray()); } } mesh.GenerateAdjacency(0.5f); mesh.ComputeNormals(); Texture texture = null; string objName = _Enc.GetString(pMesh.Objects[index2].Textures[0].InternalName); int index5 = source4[index1].Object.FindIndex(x => x.Name.Equals(objName)); if (index5 != -1) { texture = GetTextureFromFile(source4[index1].Object[index5].Texture); } _Models.Add(new tMesh(mesh, texture)); } } } } catch { } try { _Zoom = (new float[3] { source1.Max(), source2.Max(), source3.Max() }).Max() * 3f; } catch { } slideZoom.Value = (int)_Zoom * 100; }
public override void OnVertexBufferCreate(object sender, EventArgs e) { vBuff = (VertexBuffer) sender; this.verts = new CustomVertex.PositionNormalTextured[16]; // front face x y z nx ny nz tu tv verts[0] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); verts[1] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); verts[2] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); verts[3] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); // right face verts[4] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); verts[5] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); verts[6] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); verts[7] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); // back face verts[8] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f); verts[9] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f); verts[10] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); verts[11] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); // left face verts[12] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); verts[13] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); verts[14] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f); verts[15] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); // // top face // verts[16] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); // verts[17] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); // verts[18] = new CustomVertex.PositionNormalTextured( 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); // // verts[19] = new CustomVertex.PositionNormalTextured( 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); // // bottom face // verts[20] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f); // verts[21] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f); // verts[22] = new CustomVertex.PositionNormalTextured( 1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f); // // verts[23] = new CustomVertex.PositionNormalTextured( 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f); vBuff.SetData(verts,0,LockFlags.None); indexy = new short[24]; short foo = 0; for(short i = 0; i < 4; i++) { indexy[foo++] = (short) (i*4); indexy[foo++] = (short) (i*4 + 1); indexy[foo++] = (short) (i*4 + 2); indexy[foo++] = (short) (i*4); indexy[foo++] = (short) (i*4 + 3); indexy[foo++] = (short) (i*4 + 1); } iBuff = new IndexBuffer(typeof(short), indexy.Length, device, 0 /* Usage.Dynamic | Usage.WriteOnly*/, Pool.Managed); iBuff.SetData(indexy,0,LockFlags.None); this.type = PrimitiveType.TriangleList; this.count = indexy.Length/3; this.useIBuff = true; }
void fillPosNormTex(ref OBJGroup group) { List<CustomVertex.PositionNormalTextured> verts = new List<CustomVertex.PositionNormalTextured>(); List<int> indicies = new List<int>(); foreach (OBJFace f in group.faces) { int numVerts = f.vertIndices.Count; for (int i = 0; i < numVerts; i++) { bool foundMatch = false; for (int j = 0; j < verts.Count; j++) { if (verts[j].Position == positions[f.vertIndices[i]] && verts[j].Normal == normals[f.vertNormals[i]] && verts[j].Tu == texCoords[f.texCoords[i]].X && verts[j].Tv == texCoords[f.texCoords[i]].Y) { indicies.Add(j); foundMatch = true; break; } } if (foundMatch) continue; CustomVertex.PositionNormalTextured vert = new CustomVertex.PositionNormalTextured(positions[f.vertIndices[i]], normals[f.vertNormals[i]], texCoords[f.texCoords[i]].X, texCoords[f.texCoords[i]].Y); verts.Add(vert); indicies.Add(verts.Count-1); } } group.numVerts = verts.Count; group.numTris = indicies.Count / 3; group.vertexFormat = CustomVertex.PositionNormalTextured.Format; group.vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), verts.Count, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default); group.vertexBuffer.SetData(verts.ToArray(), 0, LockFlags.None); group.indexBuffer = new IndexBuffer(typeof(int), indicies.Count * sizeof(int), device, Usage.WriteOnly, Pool.Default); group.indexBuffer.SetData(indicies.ToArray(), 0, LockFlags.None); }
public CustomVertex.PositionNormalTextured[] ExportDirectX(int Col) { int count = RawFaces.Count() * 3; CustomVertex.PositionNormalTextured[] t = new CustomVertex.PositionNormalTextured[count]; int sel = 0; bool hasUVs = true; if (UVSets == null || UVSets.Count == 0) hasUVs = false; if(hasUVs) sel = UVSets[0].U.Length - 1; for (int i = 0; i < RawFaces.Count(); i++) { CustomVertex.PositionNormalTextured t2 = new CustomVertex.PositionNormalTextured(); t2.Normal = getNormal(new Vector3(Vertices[RawFaces[i].e0].x, Vertices[RawFaces[i].e0].y, Vertices[RawFaces[i].e0].z), new Vector3(Vertices[RawFaces[i].e1].x, Vertices[RawFaces[i].e1].y, Vertices[RawFaces[i].e1].z), new Vector3(Vertices[RawFaces[i].e2].x, Vertices[RawFaces[i].e2].y, Vertices[RawFaces[i].e2].z)); t2.X = Vertices[RawFaces[i].e0].x; t2.Y = Vertices[RawFaces[i].e0].y; t2.Z = Vertices[RawFaces[i].e0].z; if (hasUVs) { t2.Tu = UVSets[RawFaces[i].e0].U[sel]; t2.Tv = UVSets[RawFaces[i].e0].V[sel]; } t[i * 3] = t2; t2.X = Vertices[RawFaces[i].e1].x; t2.Y = Vertices[RawFaces[i].e1].y; t2.Z = Vertices[RawFaces[i].e1].z; if (hasUVs) { t2.Tu = UVSets[RawFaces[i].e1].U[sel]; t2.Tv = UVSets[RawFaces[i].e1].V[sel]; } t[i * 3 + 1] = t2; t2.X = Vertices[RawFaces[i].e2].x; t2.Y = Vertices[RawFaces[i].e2].y; t2.Z = Vertices[RawFaces[i].e2].z; if (hasUVs) { t2.Tu = UVSets[RawFaces[i].e2].U[sel]; t2.Tv = UVSets[RawFaces[i].e2].V[sel]; } t[i * 3 + 2] = t2; } return t; }
// compute render data; vertex and index buffer public void CalcVerticesIndices(float terrainSize) { int width = Width; int height = Height; int max = width > height ? width : height; float scale = terrainSize / (float)(max - 1); // vertices vertices = new CustomVertex.PositionNormalTextured[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int arrayIndex = y * width + x; Vector3 position = new Vector3( (float)x * scale, (float)heightMap[x, y] * scale, (float)y * scale); vertices[arrayIndex] = new CustomVertex.PositionNormalTextured( position, new Vector3(), x / (float)width, y / (float)height); } } // indices and normals indices = new short[(width - 1) * (height - 1) * 6]; for (int y = 0; y < (height - 1); y++) { for (int x = 0; x < (width - 1); x++) { int arrayIndex = (y * (width - 1) + x) * 6; int vertexIndex = y * width + x; indices[arrayIndex] = (short)vertexIndex; indices[arrayIndex + 1] = (short)(vertexIndex + 1); indices[arrayIndex + 2] = (short)(vertexIndex + width); indices[arrayIndex + 3] = (short)(vertexIndex + width); indices[arrayIndex + 4] = (short)(vertexIndex + 1); indices[arrayIndex + 5] = (short)(vertexIndex + width + 1); } } int faces = indices.Length / 3; int verts = vertices.Length; Vector3[] vertexNormals = new Vector3[verts]; for (int i = 0; i < verts; i++) { vertexNormals[i] = new Vector3(0, 0, 0); } // compute the face normals as average of adjacent edges normals (yes, that is primitive) for (int i = 0; i < faces; i++) { Vector3 edge0 = vertices[indices[i * 3]].Position - vertices[indices[i * 3 + 1]].Position; Vector3 edge1 = vertices[indices[i * 3 + 1]].Position - vertices[indices[i * 3 + 2]].Position; Vector3 faceNormal = Vector3.Normalize(Vector3.Cross(edge1, edge0)); vertexNormals[indices[i * 3]] += faceNormal; vertexNormals[indices[i * 3 + 1]] += faceNormal; vertexNormals[indices[i * 3 + 2]] += faceNormal; } // normalize to normals for (int i = 0; i < verts; i++) { vertices[i].Normal = Vector3.Normalize(vertexNormals[i]); } }
public void VertexDeclaration() { vb = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 30, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default); //из-за введения текстурных координат приходится описывать вершины во всех треугольниках vertices = new CustomVertex.PositionNormalTextured[30]; //дно vertices[0] = new CustomVertex.PositionNormalTextured(3f, 0f, 0f, 0f, 0f, -1f, 0.5f, 1f); vertices[1] = new CustomVertex.PositionNormalTextured(0f, 3f, 0f, 0f, 0f, -1f, 1f, 0.5f); vertices[2] = new CustomVertex.PositionNormalTextured(-3f, 0f, 0f, 0f, 0f, -1f, 0.5f, 0f); vertices[3] = new CustomVertex.PositionNormalTextured(-1f, -3f, 0f, 0f, 0f, -1f, 0f, 0.33333f); vertices[4] = new CustomVertex.PositionNormalTextured(1f, -3f, 0f, 0f, 0f, -1f, 0f, 0.66666f); //крыша vertices[5] = new CustomVertex.PositionNormalTextured(4f, 1f, 5f, 0f, 0f, 1f, 0.5f, 1f); vertices[6] = new CustomVertex.PositionNormalTextured(1f, 4f, 5f, 0f, 0f, 1f, 1f, 0.5f); vertices[7] = new CustomVertex.PositionNormalTextured(-2f, 1f, 5f, 0f, 0f, 1f, 0.5f, 0f); vertices[8] = new CustomVertex.PositionNormalTextured(0f, -2f, 5f, 0f, 0f, 1f, 0f, 0.33333f); vertices[9] = new CustomVertex.PositionNormalTextured(2f, -2f, 5f, 0f, 0f, 1f, 0f, 0.66666f); //первая vertices[10] = new CustomVertex.PositionNormalTextured(3f, 0f, 0f, (float)(-15 / Math.Sqrt(486)), (float)(-15 / Math.Sqrt(486)), (float)(6 / Math.Sqrt(486)), 1f, 1f); vertices[11] = new CustomVertex.PositionNormalTextured(4f, 1f, 5f, (float)(-15 / Math.Sqrt(486)), (float)(-15 / Math.Sqrt(486)), (float)(6 / Math.Sqrt(486)), 1f, 0f); vertices[12] = new CustomVertex.PositionNormalTextured(1f, 4f, 5f, (float)(-15 / Math.Sqrt(486)), (float)(-15 / Math.Sqrt(486)), (float)(6 / Math.Sqrt(486)), 0f, 0f); vertices[13] = new CustomVertex.PositionNormalTextured(0f, 3f, 0f, (float)(-15 / Math.Sqrt(486)), (float)(-15 / Math.Sqrt(486)), (float)(6 / Math.Sqrt(486)), 0f, 1f); //вторая vertices[14] = new CustomVertex.PositionNormalTextured(0f, 3f, 0f, (float)(15 / Math.Sqrt(450)), (float)(-15 / Math.Sqrt(450)), 0f, 1f, 1f); vertices[15] = new CustomVertex.PositionNormalTextured(1f, 4f, 5f, (float)(15 / Math.Sqrt(450)), (float)(-15 / Math.Sqrt(450)), 0f, 1f, 0f); vertices[16] = new CustomVertex.PositionNormalTextured(-2f, 1f, 5f, (float)(15 / Math.Sqrt(450)), (float)(-15 / Math.Sqrt(450)), 0f, 0f, 0f); vertices[17] = new CustomVertex.PositionNormalTextured(-3f, 0f, 0f, (float)(15 / Math.Sqrt(450)), (float)(-15 / Math.Sqrt(450)), 0f, 0f, 1f); //третья vertices[18] = new CustomVertex.PositionNormalTextured(-3f, 0f, 0f, (float)(15 / Math.Sqrt(350)), (float)(10 / Math.Sqrt(350)), (float)(-5 / Math.Sqrt(350)), 1f, 1f); vertices[19] = new CustomVertex.PositionNormalTextured(-2f, 1f, 5f, (float)(15 / Math.Sqrt(350)), (float)(10 / Math.Sqrt(350)), (float)(-5 / Math.Sqrt(350)), 1f, 0f); vertices[20] = new CustomVertex.PositionNormalTextured(0f, -2f, 5f, (float)(15 / Math.Sqrt(350)), (float)(10 / Math.Sqrt(350)), (float)(-5 / Math.Sqrt(350)), 0f, 0f); vertices[21] = new CustomVertex.PositionNormalTextured(-1f, -3f, 0f, (float)(15 / Math.Sqrt(350)), (float)(10 / Math.Sqrt(350)), (float)(-5 / Math.Sqrt(350)), 0f, 1f); //четвертая vertices[22] = new CustomVertex.PositionNormalTextured(-1f, -3f, 0f, 0f, (float)(10 / Math.Sqrt(104)), (float)(-2 / Math.Sqrt(104)), 1f, 1f); vertices[23] = new CustomVertex.PositionNormalTextured(0f, -2f, 5f, 0f, (float)(10 / Math.Sqrt(104)), (float)(-2 / Math.Sqrt(104)), 1f, 0f); vertices[24] = new CustomVertex.PositionNormalTextured(2f, -2f, 5f, 0f, (float)(10 / Math.Sqrt(104)), (float)(-2 / Math.Sqrt(104)), 0f, 0f); vertices[25] = new CustomVertex.PositionNormalTextured(1f, -3f, 0f, 0f, (float)(10 / Math.Sqrt(104)), (float)(-2 / Math.Sqrt(104)), 0f, 1f); //пятая vertices[26] = new CustomVertex.PositionNormalTextured(1f, -3f, 0f, (float)(-15 / Math.Sqrt(326)), (float)(10 / Math.Sqrt(326)), (float)(1 / Math.Sqrt(326)), 1f, 1f); vertices[27] = new CustomVertex.PositionNormalTextured(2f, -2f, 5f, (float)(-15 / Math.Sqrt(326)), (float)(10 / Math.Sqrt(326)), (float)(1 / Math.Sqrt(326)), 1f, 0f); vertices[28] = new CustomVertex.PositionNormalTextured(4f, 1f, 5f, (float)(-15 / Math.Sqrt(326)), (float)(10 / Math.Sqrt(326)), (float)(1 / Math.Sqrt(326)), 0f, 0f); vertices[29] = new CustomVertex.PositionNormalTextured(3f, 0f, 0f, (float)(-15 / Math.Sqrt(326)), (float)(10 / Math.Sqrt(326)), (float)(1 / Math.Sqrt(326)), 0f, 1f); vb.SetData(vertices, 0, LockFlags.None); //индексы, показывающие, как из вершин составить треугольники ib = new IndexBuffer(typeof(int), 48, device, Usage.WriteOnly, Pool.Default); indices = new int[48]; //дно indices[0] = 3; indices[1] = 2; indices[2] = 1; indices[3] = 4; indices[4] = 3; indices[5] = 1; indices[6] = 0; indices[7] = 4; indices[8] = 1; //крыша indices[9] = 8; indices[10] = 6; indices[11] = 7; indices[12] = 9; indices[13] = 6; indices[14] = 8; indices[15] = 5; indices[16] = 6; indices[17] = 9; //первая indices[18] = 13; indices[19] = 12; indices[20] = 10; indices[21] = 10; indices[22] = 12; indices[23] = 11; //вторая indices[24] = 17; indices[25] = 16; indices[26] = 14; indices[27] = 14; indices[28] = 16; indices[29] = 15; //третья indices[30] = 21; indices[31] = 20; indices[32] = 18; indices[33] = 18; indices[34] = 20; indices[35] = 19; //четвертая indices[36] = 25; indices[37] = 24; indices[38] = 22; indices[39] = 22; indices[40] = 24; indices[41] = 23; //пятая indices[42] = 29; indices[43] = 28; indices[44] = 26; indices[45] = 26; indices[46] = 28; indices[47] = 27; ib.SetData(indices, 0, LockFlags.None); }
public static void CreateSphereTriangles(Vector3 centre, double radius, int numSegments, out CustomVertex.PositionNormalTextured[] points) { int numVerts = numSegments * (numSegments / 2) * 6; points = new CustomVertex.PositionNormalTextured[numVerts]; double theta1, theta2, theta3; Vector3 e, p; if (radius < 0) { radius = -radius; } if (numSegments < 0) { numSegments = -numSegments; } int vIdx = 0; for (int j = 0; j < numSegments / 2; j++) { theta1 = j * TWOPI / numSegments - PID2; theta2 = (j + 1) * TWOPI / numSegments - PID2; for (int i = 0; i <= numSegments; i++) { theta3 = i * TWOPI / numSegments; if (i > 0) { e.X = (float)(Math.Cos(theta2) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta2); e.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); // end of T1 points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * (j + 1) / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; e.X = (float)(Math.Cos(theta1) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta1); e.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); // T2 points[vIdx].Normal = points[vIdx - 1].Normal; points[vIdx].Tu = points[vIdx - 1].Tu; points[vIdx].Tv = points[vIdx - 1].Tv; points[vIdx].Position = points[vIdx - 1].Position; vIdx++; points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * j / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; points[vIdx].Normal = points[vIdx - 5].Normal; points[vIdx].Tu = points[vIdx - 5].Tu; points[vIdx].Tv = points[vIdx - 5].Tv; points[vIdx].Position = points[vIdx - 5].Position; vIdx++; // start of T1 if (i < numSegments /*- 1*/) { points[vIdx].Normal = points[vIdx - 2].Normal; points[vIdx].Tu = points[vIdx - 2].Tu; points[vIdx].Tv = points[vIdx - 2].Tv; points[vIdx].Position = points[vIdx - 2].Position; vIdx++; points[vIdx].Normal = points[vIdx - 4].Normal; points[vIdx].Tu = points[vIdx - 4].Tu; points[vIdx].Tv = points[vIdx - 4].Tv; points[vIdx].Position = points[vIdx - 4].Position; vIdx++; } } else { e.X = (float)(Math.Cos(theta1) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta1); e.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * j / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; e.X = (float)(Math.Cos(theta2) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta2); e.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * (j + 1) / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; } } } }
public static void CreateSphereTriangleStrips(Vector3 centre, double radius, int numSegments, out CustomVertex.PositionNormalTextured[] points, out int numStrips, out int vertsPerStrip, out int primsPerStrip) { int numVerts = numSegments * (numSegments / 2) * 3; points = new CustomVertex.PositionNormalTextured[numVerts]; numStrips = numSegments / 2; vertsPerStrip = (numSegments * 2) + 2; primsPerStrip = numSegments * 2; int i, j; double theta1, theta2, theta3; Vector3 e, p; if (radius < 0) { radius = -radius; } if (numSegments < 0) { numSegments = -numSegments; } int vIdx = 0; for (j = 0; j < numSegments / 2; j++) { theta1 = j * TWOPI / numSegments - PID2; theta2 = (j + 1) * TWOPI / numSegments - PID2; for (i = 0; i <= numSegments; i++) { theta3 = i * TWOPI / numSegments; e.X = (float)(Math.Cos(theta2) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta2); e.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * (j + 1) / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; e.X = (float)(Math.Cos(theta1) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta1); e.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * j / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; } } }
public static void SaveMeshVertices(ref AnimatTools.Interfaces.StdXml oXml, string strName, Mesh myMesh, bool bSaveIndices) { CustomVertex.PositionNormalTextured[] cvVerts = new CustomVertex.PositionNormalTextured[myMesh.NumberVertices]; oXml.AddChildElement(strName); oXml.IntoElem(); //Into the mesh GraphicsStream buffer = myMesh.LockVertexBuffer(LockFlags.ReadOnly); AnimatTools.Framework.Vec3d vVertex = new AnimatTools.Framework.Vec3d(null); for(int i=0; i<myMesh.NumberVertices; i++) { buffer.Position = i * myMesh.NumberBytesPerVertex; cvVerts[i] = (CustomVertex.PositionNormalTextured)buffer.Read(typeof(CustomVertex.PositionNormalTextured)); //System.Diagnostics.Debug.WriteLine("v " + cvVerts[i].X + " " + cvVerts[i].Y + " " + cvVerts[i].Z); vVertex.X = cvVerts[i].X;// - this.AbsoluteLocation.X; vVertex.Y = cvVerts[i].Y;// - this.AbsoluteLocation.Y; vVertex.Z = cvVerts[i].Z;// - this.AbsoluteLocation.Z; Util.SaveVector(ref oXml, "Vector", vVertex); //Debug.WriteLine("data.Write(new CustomVertex.PositionTextured(" + vVertex.X + "f, " + vVertex.Y + "f, " + vVertex.Z + "f, 0f, 0f));"); //if(i%3 == 0) Debug.WriteLine(""); //Debug.WriteLine("V: " + i + " (" + cvVerts[i].X + ", " + cvVerts[i].Y + ", " + cvVerts[i].Z + ", " + cvVerts[i].Nx + ", " + cvVerts[i].Ny + ", " + cvVerts[i].Nz + ")"); } myMesh.UnlockVertexBuffer(); if(bSaveIndices) { using (IndexBuffer ib = myMesh.IndexBuffer) { GraphicsStream gs = ib.Lock(0, myMesh.NumberFaces*3*2, LockFlags.ReadOnly); string strIndex = ""; short iIndex; for(int i=0; i<myMesh.NumberFaces*3; i++) { gs.Position = i * 2; iIndex = (short) gs.Read(typeof(short)); strIndex += iIndex.ToString(); if(i<gs.Length-1) strIndex += ","; } oXml.AddChildElement("IndexBuffer", strIndex); ib.Unlock(); } } oXml.OutOfElem(); //Out of the mesh }
private void RebuildAsync(Object deviceObj) { try { Device device = (Device)deviceObj; // Rebuild if (_line.Equals("")) { _lineSprite = null; _valid = true; } else { try { int firstTick = Environment.TickCount; System.Drawing.Font font = new System.Drawing.Font(_fontFace, _fontSize); Bitmap b = new Bitmap(_lineWidth, _lineHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(b); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, b.Width, b.Height)); g.DrawString(_displayString, font, new SolidBrush(Color.White), new PointF(0, 0)); //TextRenderer.DrawText(g, _displayString, font, new Point(0, 0), Color.White); _lineTexture = Texture.FromBitmap(device, b, Usage.None, Pool.Managed); //_lineTexture = new Texture(device, (int)_lineWidth * (int)Math.Pow(2.0, (double)mipLevels), (int)_lineHeight * (int)Math.Pow(2.0, (double)mipLevels), mipLevels + 1, Usage.RenderTarget, Format.Unknown, Pool.Default); //Surface s = _lineTexture.GetSurfaceLevel(mipLevels); //SurfaceLoader.FromSurface(s, Surface.FromBitmap(device, b, Pool.Default), Filter.Box, 0xFF0000); g.Dispose(); //for (int i = 1; i <= mipLevels; i++) //{ // int width = _lineWidth * (int)Math.Pow(2.0, (double)i); // int height = _lineHeight * (int)Math.Pow(2, (double)i); // b = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // font = new System.Drawing.Font(_fontFace, _fontSize * (float)Math.Pow(2, (double)i)); // g = Graphics.FromImage(b); // g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; // g.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, b.Width, b.Height)); // g.DrawString(displayString, font, new SolidBrush(Color.White), new PointF(0, 0)); // s = _lineTexture.GetSurfaceLevel(mipLevels - i); // SurfaceLoader.FromSurface(s, Surface.FromBitmap(device, b, Pool.Default), Filter.Box, 0xFF0000); // g.Dispose(); //} // Set up the material _lineMaterial = new Material(); _lineMaterial.Diffuse = _line.Color; //_lineMaterial.Ambient = GetColor(_line.Type); // Set up the rectangular mesh CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[4]; verts[0].Position = new Vector3(0, 0, -_lineHeight); verts[0].Normal = new Vector3(0, 1, 0); verts[0].Tu = 0; verts[0].Tv = 1; verts[1].Position = new Vector3(_lineWidth, 0, -_lineHeight); verts[1].Normal = new Vector3(0, 1, 0); verts[1].Tu = 1; verts[1].Tv = 1; verts[2].Position = new Vector3(_lineWidth, 0, 0); verts[2].Normal = new Vector3(0, 1, 0); verts[2].Tu = 1; verts[2].Tv = 0; verts[3].Position = new Vector3(0, 0, 0); verts[3].Normal = new Vector3(0, 1, 0); verts[3].Tu = 0; verts[3].Tv = 0; AttributeRange[] attributes = new AttributeRange[1]; attributes[0].AttributeId = 0; attributes[0].FaceCount = 2; attributes[0].FaceStart = 0; attributes[0].VertexCount = 4; attributes[0].VertexStart = 0; short[] indices = new short[] { 0, 1, 2, 0, 2, 3 }; _lineSprite = new Mesh(2, 4, 0, CustomVertex.PositionNormalTextured.Format, device); _lineSprite.SetVertexBufferData(verts, LockFlags.Discard); _lineSprite.SetIndexBufferData(indices, LockFlags.Discard); _lineSprite.SetAttributeTable(attributes); //int[] adjacency = new int[_lineSprite.NumberFaces * 3]; //_lineSprite.GenerateAdjacency(0.01F, adjacency); //_lineSprite.OptimizeInPlace(MeshFlags.OptimizeVertexCache, adjacency); _valid = true; } catch (Exception) { _valid = false; _lineTexture = null; _lineSprite = null; return; } } } catch (Exception) { _valid = false; _lineTexture = null; _lineSprite = null; } finally { Animate(0); _building = false; } }
/// <summary> /// Creates a PositionNormalTextured ring centered on zero in the equatorial plane /// </summary> /// <param name="device">The current direct3D drawing device.</param> /// <param name="radius1">The ring inner radius</param> /// <param name="radius2">The ring outter radius</param> /// <param name="slices">Number of slices (angular resolution).</param> /// <param name="stacks">Number of stacks (radial resolution)</param> /// <returns></returns> /// <remarks> /// Number of vertices in the ring will be (slices+1)*(stacks+1)<br/> /// Number of faces :slices*stacks*2 /// Number of Indexes : Number of faces * 3; /// </remarks> private Mesh TexturedRings(Device device, float radius1, float radius2, int slices, int stacks) { int numVertices = (slices + 1) * (stacks + 1); int numFaces = slices * stacks * 2; int indexCount = numFaces * 3; float radiusStep = (radius2 - radius1) / stacks; Mesh mesh = new Mesh(numFaces, numVertices, MeshFlags.Managed, CustomVertex.PositionNormalTextured.Format, device); // Get the mesh vertex buffer. int[] ranks = new int[1]; ranks[0] = mesh.NumberVertices; System.Array arr = mesh.VertexBuffer.Lock(0, typeof(CustomVertex.PositionNormalTextured), LockFlags.None, ranks); // Set the vertex buffer double latitude = 0; int vertIndex = 0; for (int stack = 0; stack <= stacks; stack++) { for (int slice = 0; slice <= slices; slice++) { CustomVertex.PositionNormalTextured pnt = new CustomVertex.PositionNormalTextured(); double longitude = 180 - ((float)slice / slices * (float)360); Vector3 v = MathEngine.SphericalToCartesian(latitude, longitude, radius1 + radiusStep * stack); pnt.X = v.X; pnt.Y = v.Y; pnt.Z = v.Z; pnt.Tu = (float)stack / stacks; pnt.Tv = 0.0f; 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); mesh.ComputeNormals(); return mesh; }
public static CpuDEMSubGeometry CreatePointList(RectangleGroupQuadTree.GroupNode node, Device gDevice, int sampleInterval, Size totalAreaSz, float minValue, float maxValue) { // BUG: Not working right for < native? int xSamples = node.NodeArea.Width / sampleInterval; int ySamples = node.NodeArea.Height / sampleInterval; bool blendStartX = (node.NodeArea.Left != 0); bool blendEndX = (node.NodeArea.Right != totalAreaSz.Width); bool blendStartY = (node.NodeArea.Top != 0); bool blendEndY = (node.NodeArea.Bottom != totalAreaSz.Height); Size iBufSize = new Size(xSamples, ySamples); int xAdditional = 0; int yAdditional = 0; if (!blendStartX) { xAdditional++; } if (!blendEndX) { xAdditional++; } if (!blendStartY) { yAdditional++; } if (!blendEndY) { yAdditional++; } // create buffers VertexBuffer vBuffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), (xSamples + xAdditional) * (ySamples + yAdditional), gDevice, Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Managed); CustomVertex.PositionNormalTextured[] verts = (CustomVertex.PositionNormalTextured[])vBuffer.Lock(0, LockFlags.None); // fill x+z and texCoord components independant of y heights float yActual = /*-2.5f +*/ ((float)node.NodeArea.Top / totalAreaSz.Height * 5f); float xActInc = ((float)node.NodeArea.Width / totalAreaSz.Width * 5) / (xSamples - 1); float yActInc = ((float)node.NodeArea.Height / totalAreaSz.Height * 5) / (ySamples - 1); int vPos = 0; float ty = 0; float tyInc = 1f / (ySamples - 1); for (int y = 0; y < ySamples; y++) { float xActual = /*-2.5f + */ ((float)node.NodeArea.Left / totalAreaSz.Width * 5f); float tx = 0; float txInc = 1f / (xSamples - 1); for (int x = 0; x < xSamples; x++) { verts[vPos++] = new CustomVertex.PositionNormalTextured(xActual, 0, yActual, 0, 0, 0, tx, ty); xActual += xActInc; tx += txInc; } yActual += yActInc; ty += tyInc; } // skirts IndexBuffer[] skirts = new IndexBuffer[xAdditional + yAdditional]; int skirtIdx = 0; if (!blendStartX) { yActual = /*-2.5f +*/ ((float)node.NodeArea.Top / totalAreaSz.Height * 5f); ty = 0; for (int y = 0; y < ySamples; y++) { float xActual = /*-2.5f +*/ ((float)node.NodeArea.Left / totalAreaSz.Width * 5f); verts[vPos++] = new CustomVertex.PositionNormalTextured(xActual, -0.5f, yActual, 0, 0, 0, -0.1f, ty); yActual += yActInc; ty += tyInc; } skirts[skirtIdx] = CreateTriStripSkirtIndices(xSamples, gDevice, 0, skirtIdx); skirtIdx++; } if (!blendEndX) { yActual = /*-2.5f +*/ ((float)node.NodeArea.Top / totalAreaSz.Height * 5f); ty = 0; for (int y = 0; y < ySamples; y++) { float xActual = /*-2.5f +*/ ((float)node.NodeArea.Right / totalAreaSz.Width * 5); verts[vPos++] = new CustomVertex.PositionNormalTextured(xActual, -0.5f, yActual, 0, 0, 0, 1.1f, ty); yActual += yActInc; ty += tyInc; } skirts[skirtIdx] = CreateTriStripSkirtIndices(xSamples, gDevice, 1, skirtIdx); skirtIdx++; } if (!blendStartY) { float xActual = /*-2.5f +*/ ((float)node.NodeArea.Left / totalAreaSz.Width * 5f); float tx = 0; for (int y = 0; y < ySamples; y++) { yActual = /*-2.5f +*/ ((float)node.NodeArea.Top / totalAreaSz.Height * 5f); verts[vPos++] = new CustomVertex.PositionNormalTextured(xActual, -0.5f, yActual, 0, 0, 0, tx, -0.1f); xActual += xActInc; tx += tyInc; } skirts[skirtIdx] = CreateTriStripSkirtIndices(xSamples, gDevice, 2, skirtIdx); skirtIdx++; } if (!blendEndY) { float xActual = /*-2.5f +*/ ((float)node.NodeArea.Left / totalAreaSz.Width * 5f); float tx = 0; for (int y = 0; y < ySamples; y++) { yActual = /*-2.5f +*/ ((float)node.NodeArea.Bottom / totalAreaSz.Height * 5f); verts[vPos++] = new CustomVertex.PositionNormalTextured(xActual, -0.5f, yActual, 0, 0, 0, tx, 1.1f); xActual += xActInc; tx += tyInc; } skirts[skirtIdx] = CreateTriStripSkirtIndices(xSamples, gDevice, 3, skirtIdx); skirtIdx++; } SizeF onePixel = new SizeF(1f / (node.NodeArea.Width - 1), 1f / (node.NodeArea.Height - 1)); // fill in from sample rectangles only float[] heights = new float[xSamples * ySamples]; foreach (DataArea area in node.Rectangles) { SimpleRasterSampler sampler = new MultiSampleRasterSampler(area, sampleInterval, xSamples); SimpleRasterSampler singleSampler = new SimpleRasterSampler(area, sampleInterval); // TODO: Sample only area not 0 -> (1-1px%) float xAdv = 1f / (xSamples - 1); float yAdv = 1f / (ySamples - 1); float yPos = 0; vPos = 0; int yStart = 0; int yEnd = ySamples; // y edge if (blendStartY) { float xPos = 0; int xStart = 0; int xEnd = xSamples; // xy edge float rawValue1, rawValue2, rawValue3, rawValue4; float sVal, value; if (blendStartX) { if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos - onePixel.Width, yPos); rawValue3 = singleSampler.GetByte(xPos, yPos - onePixel.Height); rawValue4 = singleSampler.GetByte(xPos - onePixel.Width, yPos - onePixel.Height); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos - onePixel.Width, yPos]; rawValue3 = singleSampler[xPos, yPos - onePixel.Height]; rawValue4 = singleSampler[xPos - onePixel.Width, yPos - onePixel.Height]; } sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue) + (rawValue3 / maxValue) + (rawValue4 / maxValue)) / 4; value = -0.5f + sVal; heights[vPos++] = value; xPos += xAdv; xStart++; } if (blendEndX) { xEnd--; } // do normal range for (int x = xStart; x < xEnd; x++) { if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos, yPos - onePixel.Height); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos, yPos - onePixel.Height]; } sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue)) / 2; value = -0.5f + sVal; heights[vPos++] = value; xPos += xAdv; } // xy edge if (blendEndX) { // take 2 samples if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos + onePixel.Width, yPos); rawValue3 = singleSampler.GetByte(xPos, yPos - onePixel.Height); rawValue4 = singleSampler.GetByte(xPos + onePixel.Width, yPos - onePixel.Height); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos + onePixel.Width, yPos]; rawValue3 = singleSampler[xPos, yPos - onePixel.Height]; rawValue4 = singleSampler[xPos + onePixel.Width, yPos - onePixel.Height]; } sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue) + (rawValue3 / maxValue) + (rawValue4 / maxValue)) / 4; value = -0.5f + sVal; heights[vPos++] = value; } yPos += yAdv; yStart++; } if (blendEndY) { yEnd--; } // normal range + x exclusive edges for (int y = yStart; y < yEnd; y++) { float xPos = 0; int xStart = 0; int xEnd = xSamples; if (blendStartX) { // take 2 samples float rawValue1, rawValue2; if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos - onePixel.Width, yPos); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos - onePixel.Width, yPos]; } float sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue)) / 2; float value = -0.5f + sVal; heights[vPos++] = value; xPos += xAdv; xStart++; } if (blendEndX) { xEnd--; } // do normal range for (int x = xStart; x < xEnd; x++) { float rawValue; if (sampler.DataSource is ByteArea) { rawValue = sampler.GetByte(xPos, yPos); } else { rawValue = sampler[xPos, yPos]; } float sVal = rawValue / maxValue; float value = -0.5f + sVal; heights[vPos++] = value; xPos += xAdv; } if (blendEndX) { // take 2 samples float rawValue1, rawValue2; if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos + onePixel.Width, yPos); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos + onePixel.Width, yPos]; } float sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue)) / 2; float value = -0.5f + sVal; heights[vPos++] = value; } yPos += yAdv; } // y edge if (blendEndY) { float xPos = 0; int xStart = 0; int xEnd = xSamples; // xy egde float rawValue1, rawValue2, rawValue3, rawValue4; float sVal, value; if (blendStartX) { if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos - onePixel.Width, yPos); rawValue3 = singleSampler.GetByte(xPos, yPos + onePixel.Height); rawValue4 = singleSampler.GetByte(xPos - onePixel.Width, yPos + onePixel.Height); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos - onePixel.Width, yPos]; rawValue3 = singleSampler[xPos, yPos + onePixel.Height]; rawValue4 = singleSampler[xPos - onePixel.Width, yPos + onePixel.Height]; } sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue) + (rawValue3 / maxValue) + (rawValue4 / maxValue)) / 4; value = -0.5f + sVal; heights[vPos++] = value; xPos += xAdv; xStart++; } if (blendEndX) { xEnd--; } // do normal range for (int x = xStart; x < xEnd; x++) { if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos, yPos + onePixel.Height); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos, yPos + onePixel.Height]; } sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue)) / 2; value = -0.5f + sVal; heights[vPos++] = value; xPos += xAdv; } // xy edge if (blendEndX) { if (sampler.DataSource is ByteArea) { rawValue1 = singleSampler.GetByte(xPos, yPos); rawValue2 = singleSampler.GetByte(xPos + onePixel.Width, yPos); rawValue3 = singleSampler.GetByte(xPos, yPos + onePixel.Height); rawValue4 = singleSampler.GetByte(xPos + onePixel.Width, yPos + onePixel.Height); } else { rawValue1 = singleSampler[xPos, yPos]; rawValue2 = singleSampler[xPos + onePixel.Width, yPos]; rawValue3 = singleSampler[xPos, yPos + onePixel.Height]; rawValue4 = singleSampler[xPos + onePixel.Width, yPos + onePixel.Height]; } sVal = ((rawValue1 / maxValue) + (rawValue2 / maxValue) + (rawValue3 / maxValue) + (rawValue4 / maxValue)) / 4; value = -0.5f + sVal; heights[vPos++] = value; } } } // pick up additional heights for internal borders // generate triangle normals from heights Vector3[] vNormals = new Vector3[xSamples * ySamples]; vPos = 0; Vector3 v0 = new Vector3(0, 0, 0); Vector3 v1 = new Vector3(0, 0, 1); Vector3 v2 = new Vector3(1, 0, 0); Vector3 v3 = new Vector3(1, 0, 1); for (int y = 0; y < ySamples - 1; y++) { for (int x = 0; x < xSamples - 1; x++) { v0.Y = heights[vPos]; v1.Y = heights[vPos + xSamples]; v2.Y = heights[vPos + 1]; v3.Y = heights[vPos + xSamples + 1]; Vector3 e1 = v1 - v0; Vector3 e2 = v2 - v0; Vector3 normal = Vector3.Normalize(Vector3.Cross(e1, e2)); vNormals[vPos] += normal; vNormals[vPos + xSamples] += normal; vNormals[vPos + 1] += normal; e1 = v1 - v2; e2 = v3 - v2; normal = Vector3.Normalize(Vector3.Cross(e1, e2)); vNormals[vPos + xSamples] += normal; vNormals[vPos + 1] += normal; vNormals[vPos + xSamples + 1] += normal; vPos++; } } // calculate vertex normals and input heights into vBuffer vPos = 0; for (int x = 0; x < xSamples; x++) { Vector3 result = vNormals[vPos] * (1f / 4f); verts[vPos].Y = heights[vPos]; verts[vPos].Normal = result; vPos++; } for (int y = 1; y < ySamples - 1; y++) { Vector3 result = vNormals[vPos] * (1f / 3f); verts[vPos].Y = heights[vPos]; verts[vPos].Normal = result; vPos++; for (int x = 1; x < xSamples - 1; x++) { result = vNormals[vPos] * (1f / 6f); verts[vPos].Y = heights[vPos]; verts[vPos].Normal = result; vPos++; } result = vNormals[vPos] * (1f / 3f); verts[vPos].Y = heights[vPos]; verts[vPos].Normal = result; vPos++; } for (int x = 0; x < xSamples; x++) { Vector3 result = vNormals[vPos] * (1f / 4f); verts[vPos].Y = heights[vPos]; verts[vPos].Normal = result; vPos++; } vBuffer.Unlock(); CpuDEMSubGeometry geom = new CpuDEMSubGeometry(); geom.vBuffer = vBuffer; geom.iBufSize = iBufSize; geom.skirts = skirts; return(geom); }
/// <summary> /// Write myself to a vertex buffer as a pair of triangles /// </summary> /// <param name="stream"></param> private void Write(GraphicsStream stream) { // Get a local copy of the untransformed quad CustomVertex.PositionNormalTextured[] quad = new CustomVertex.PositionNormalTextured[4]; for (int v=0; v<4; v++) { quad[v] = info.quad[v]; } // calculate frame number if (info.frameRate!=0) // if no frame rate, frame represents an unanimated variant { frame += info.frameRate * Scene.ElapsedTime; frame %= info.numFrames; } float wholeFrame = (int)frame; // define the part of the texture to display this frame, in texture coordinates float left = wholeFrame * info.width / texWidth; // fraction of the texture at which this frame starts float right = (wholeFrame+1.0f) * info.width / texWidth; float top = info.top / texHeight; // fraction of the texture at which this row starts float bot = (info.top + info.height) / texHeight; const float border = 0.001f; // close in a little, to prevent overrunning sprite edges left += border; right -= border; top += border; bot -= border; quad[0].Tu = left; quad[0].Tv = top; quad[1].Tu = right; quad[1].Tv = top; quad[2].Tu = left; quad[2].Tv = bot; quad[3].Tu = right; quad[3].Tv = bot; // Get a matrix that will rotate to face camera (around yaw axis only) and then translate into world coordinates Matrix trans = facingMatrix * Matrix.Translation(location); // We have to transform the vertices ourselves, since there are many sprites in each vertex buffer for (int v=0; v<4; v++) { // Transform the vertex quad[v].Position = Vector3.TransformCoordinate(quad[v].Position,trans); // Transform the normal quad[v].Normal = Vector3.TransformNormal(quad[v].Normal,trans); } // Add this quad's two triangles to the vertex buffer stream.Write(quad[0]); stream.Write(quad[1]); stream.Write(quad[2]); stream.Write(quad[3]); stream.Write(quad[2]); stream.Write(quad[1]); }
private void LoadColladaMesh(DrawArgs drawArgs) { XmlDocument colladaDoc = new XmlDocument(); colladaDoc.Load(meshFileName); XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(colladaDoc.NameTable); xmlnsManager.AddNamespace("c", colladaDoc.GetElementsByTagName("COLLADA")[0].NamespaceURI); int meshCount = colladaDoc.SelectNodes("//c:COLLADA/c:library_geometries/c:geometry/c:mesh", xmlnsManager).Count; if (meshCount == 0) { return; } if (m_meshElems != null) { foreach (MeshElem me in m_meshElems) { if (me.mesh != null) { me.mesh.Dispose(); } if (me.meshTextures != null) { foreach (Texture t in me.meshTextures) { if (t != null) { t.Dispose(); } } } } } m_meshElems = new MeshElem[meshCount]; for (int j = 0; j < meshCount; j++) { XmlNode meshNode = colladaDoc.SelectNodes( "//c:COLLADA/c:library_geometries/c:geometry/c:mesh", xmlnsManager)[j]; Matrix transform = Matrix.Identity; string sGeometryId = meshNode.SelectNodes("../@id", xmlnsManager)[0].Value; if (colladaDoc.SelectNodes("//c:COLLADA/c:library_visual_scenes/c:visual_scene/c:node" + "[c:instance_geometry/@url='#" + sGeometryId + "']", xmlnsManager).Count == 1) { XmlNode sceneNode = colladaDoc.SelectNodes("//c:COLLADA/c:library_visual_scenes/c:visual_scene/c:node" + "[c:instance_geometry/@url='#" + sGeometryId + "']", xmlnsManager)[0]; foreach (XmlNode childNode in sceneNode.ChildNodes) { Matrix m; if (childNode.Name == "translate") { string[] translateParams = childNode.InnerText.Trim().Split(' '); m = Matrix.Translation(new Vector3( System.Decimal.ToSingle(System.Decimal.Parse( translateParams[0], System.Globalization.NumberStyles.Any)), System.Decimal.ToSingle(System.Decimal.Parse( translateParams[1], System.Globalization.NumberStyles.Any)), System.Decimal.ToSingle(System.Decimal.Parse( translateParams[2], System.Globalization.NumberStyles.Any)))); } else if (childNode.Name == "rotate") { string[] rotateParams = childNode.InnerText.Trim().Split(' '); m = Matrix.RotationAxis( new Vector3( System.Decimal.ToSingle(System.Decimal.Parse( rotateParams[0], System.Globalization.NumberStyles.Any)), System.Decimal.ToSingle(System.Decimal.Parse( rotateParams[1], System.Globalization.NumberStyles.Any)), System.Decimal.ToSingle(System.Decimal.Parse( rotateParams[2], System.Globalization.NumberStyles.Any))), (float)Math.PI * System.Decimal.ToSingle(System.Decimal.Parse( rotateParams[3], System.Globalization.NumberStyles.Any)) / 180.0f); } else if (childNode.Name == "scale") { string[] scaleParams = childNode.InnerText.Trim().Split(' '); m = Matrix.Scaling(new Vector3( System.Decimal.ToSingle(System.Decimal.Parse( scaleParams[0], System.Globalization.NumberStyles.Any)), System.Decimal.ToSingle(System.Decimal.Parse( scaleParams[1], System.Globalization.NumberStyles.Any)), System.Decimal.ToSingle(System.Decimal.Parse( scaleParams[2], System.Globalization.NumberStyles.Any)))); } else { continue; } transform = Matrix.Multiply(m, transform); } } string sVertSource = meshNode.SelectNodes( "c:vertices/c:input[@semantic='POSITION']/@source", xmlnsManager)[0].Value; int iVertCount = System.Decimal.ToInt32(System.Decimal.Parse( meshNode.SelectNodes( "c:source[@id='" + sVertSource.Substring(1) + "']/c:float_array/@count", xmlnsManager)[0].Value)) / 3; string[] vertCoords = meshNode.SelectNodes( "c:source[@id='" + sVertSource.Substring(1) + "']/c:float_array", xmlnsManager)[0].InnerText.Trim().Split(' '); CustomVertex.PositionNormalTextured[] vertices = new CustomVertex.PositionNormalTextured[iVertCount]; Vector3 v = new Vector3(); for (int i = 0; i < iVertCount; i++) { v.X = System.Decimal.ToSingle(System.Decimal.Parse(vertCoords[i * 3 + 0], System.Globalization.NumberStyles.Any)); v.Y = System.Decimal.ToSingle(System.Decimal.Parse(vertCoords[i * 3 + 1], System.Globalization.NumberStyles.Any)); v.Z = System.Decimal.ToSingle(System.Decimal.Parse(vertCoords[i * 3 + 2], System.Globalization.NumberStyles.Any)); v.TransformCoordinate(transform); vertices[i] = new CustomVertex.PositionNormalTextured( v.X, v.Y, v.Z, 0.0f, 0.0f, 0.0f, v.X, v.Y); } int iFaceCount = System.Decimal.ToInt32(System.Decimal.Parse( meshNode.SelectNodes( "c:triangles/@count", xmlnsManager)[0].Value)); string[] triVertIndicesStr = meshNode.SelectNodes( "c:triangles/c:p", xmlnsManager)[0].InnerText.Trim().Split(' ');; short[] triVertIndices = new short[triVertIndicesStr.Length]; for (int i = 0; i < triVertIndicesStr.Length; i++) { triVertIndices[i] = System.Decimal.ToInt16(System.Decimal.Parse(triVertIndicesStr[i])); } m_meshElems[j] = new MeshElem(); m_meshElems[j].mesh = new Mesh(iFaceCount, iVertCount, 0, CustomVertex.PositionNormalTextured.Format, drawArgs.device); m_meshElems[j].mesh.SetVertexBufferData(vertices, LockFlags.None); m_meshElems[j].mesh.SetIndexBufferData(triVertIndices, LockFlags.None); int[] adjacency = new int[m_meshElems[j].mesh.NumberFaces * 3]; m_meshElems[j].mesh.GenerateAdjacency(0.000000001F, adjacency); m_meshElems[j].mesh.OptimizeInPlace(MeshFlags.OptimizeVertexCache, adjacency); m_meshElems[j].mesh.ComputeNormals(); int numSubSets = m_meshElems[j].mesh.GetAttributeTable().Length; m_meshElems[j].meshTextures = new Texture[numSubSets]; m_meshElems[j].meshMaterials = new Material[numSubSets]; for (int i = 0; i < numSubSets; i++) { m_meshElems[j].meshMaterials[i].Ambient = Color.FromArgb(255, 255, 43, 48); m_meshElems[j].meshMaterials[i].Diffuse = Color.FromArgb(255, 155, 113, 148); m_meshElems[j].meshMaterials[i].Emissive = Color.FromArgb(255, 255, 143, 98); m_meshElems[j].meshMaterials[i].Specular = Color.FromArgb(255, 155, 243, 48); } } }
protected CustomVertex.PositionNormalTextured[] createTerrainVertices(int totalVertices) { //Devuelve un array con posición, normal (fija), y coord. de textura de cada vértice int width = HeightmapData.GetLength(0); int length = HeightmapData.GetLength(1); CustomVertex.PositionNormalTextured[] terrainVertices = new CustomVertex.PositionNormalTextured[width * length]; int i = 0; for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++) { Vector3 position = new Vector3(Position.X + x * ScaleXZ, Position.Y + HeightmapData[x, z] * ScaleY, Position.Z + z * ScaleXZ); Vector3 normal = new Vector3(0, 0, 1); Vector2 texCoord = new Vector2((float)x / 30.0f, (float)z / 30.0f); terrainVertices[i++] = new CustomVertex.PositionNormalTextured(position, normal, texCoord.X, texCoord.Y); } } return terrainVertices; }
public void render(Effect effect, CScene T, CShip S) { var device = D3DDevice.Instance.Device; int pos_en_ruta = S.pos_en_ruta; float dr = T.ancho_ruta; TGCVector3 Normal = T.Normal[pos_en_ruta]; TGCVector3 Binormal = T.Binormal[pos_en_ruta]; TGCVector3 Tangent = T.Tangent[pos_en_ruta]; int cant_tri = 0; int dataIdx = 0; int cant_bandas = 200; float M = 1000000.0f; for (int j = 0; j < cant_bandas; j++) { float ei = fft.coef(2 * j) / M; float y = 40 + ei * 1230; float x0 = 2 * dr * (float)j / (float)cant_bandas - dr - 5; float x1 = 2 * dr * (float)(j + 1) / (float)cant_bandas - dr + 5; TGCVector3 p0, p1, p2, p3; float dt = -20; p0 = S.posC - Binormal * x0 - Normal * 5 + Tangent * dt; p1 = S.posC - Binormal * x1 - Normal * 5 + Tangent * dt; p2 = p0 + Tangent * y; p3 = p1 + Tangent * y; vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p0, Normal, 0, 0); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p1, Normal, 1, 0); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p2, Normal, 0, 1); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p1, Normal, 1, 0); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p2, Normal, 0, 1); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p3, Normal, 1, 1); cant_tri += 2; x0 = 2 * dr * (float)j / (float)cant_bandas - dr; x1 = 2 * dr * (float)(j + 1) / (float)cant_bandas - dr; p0 = S.posC - Binormal * x0 - Normal * 5 + Tangent * dt; p1 = S.posC - Binormal * x1 - Normal * 5 + Tangent * dt; p2 = p0 + Tangent * y; p3 = p1 + Tangent * y; vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p0, Normal, 0, 0); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p1, Normal, 1, 0); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p2, Normal, 0, 1); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p1, Normal, 1, 0); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p2, Normal, 0, 1); vb_data[dataIdx++] = new CustomVertex.PositionNormalTextured(p3, Normal, 1, 1); cant_tri += 2; } vb.SetData(vb_data, 0, LockFlags.None); device.SetStreamSource(0, vb, 0); device.VertexFormat = CustomVertex.PositionNormalTextured.Format; effect.Technique = "GlowBar"; effect.SetValue("cube_color", TGCVector3.Vector3ToFloat4Array(new TGCVector3(1, 0.3f, 0.3f))); device.RenderState.AlphaBlendEnable = true; device.RenderState.ZBufferEnable = false; int numPasses = effect.Begin(0); for (var n = 0; n < numPasses; n++) { effect.BeginPass(n); device.DrawPrimitives(PrimitiveType.TriangleList, 0, cant_tri); effect.EndPass(); } effect.End(); device.RenderState.ZBufferEnable = true; }
public void loadHeightmap(string heightmapPath, float pscaleXZ, float pscaleY, TGCVector3 center) { scaleXZ = pscaleXZ; scaleY = pscaleY; Device d3dDevice = D3DDevice.Instance.Device; this.center = center; //Dispose de VertexBuffer anterior, si habia if (vbTerrain != null && !vbTerrain.Disposed) { vbTerrain.Dispose(); } //cargar heightmap heightmapData = loadHeightMap(d3dDevice, heightmapPath); float width = heightmapData.GetLength(0); float length = heightmapData.GetLength(1); //Crear vertexBuffer totalVertices = 2 * 3 * (heightmapData.GetLength(0) + 1) * (heightmapData.GetLength(1) + 1); totalVertices *= (int)ki * (int)kj; vbTerrain = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), totalVertices, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); //Cargar vertices int dataIdx = 0; CustomVertex.PositionNormalTextured[] data = new CustomVertex.PositionNormalTextured[totalVertices]; center.X = center.X * scaleXZ - (width / 2) * scaleXZ; center.Y = center.Y * scaleY; center.Z = center.Z * scaleXZ - (length / 2) * scaleXZ; for (int i = 0; i < width - 1; i++) { for (int j = 0; j < length - 1; j++) { //Vertices TGCVector3 v1 = new TGCVector3(center.X + i * scaleXZ, center.Y + heightmapData[i, j] * scaleY, center.Z + j * scaleXZ); TGCVector3 v2 = new TGCVector3(center.X + i * scaleXZ, center.Y + heightmapData[i, j + 1] * scaleY, center.Z + (j + 1) * scaleXZ); TGCVector3 v3 = new TGCVector3(center.X + (i + 1) * scaleXZ, center.Y + heightmapData[i + 1, j] * scaleY, center.Z + j * scaleXZ); TGCVector3 v4 = new TGCVector3(center.X + (i + 1) * scaleXZ, center.Y + heightmapData[i + 1, j + 1] * scaleY, center.Z + (j + 1) * scaleXZ); //Coordendas de textura TGCVector2 t1 = new TGCVector2(ftex * i / width, ftex * j / length); TGCVector2 t2 = new TGCVector2(ftex * i / width, ftex * (j + 1) / length); TGCVector2 t3 = new TGCVector2(ftex * (i + 1) / width, ftex * j / length); TGCVector2 t4 = new TGCVector2(ftex * (i + 1) / width, ftex * (j + 1) / length); //Cargar triangulo 1 TGCVector3 n1 = TGCVector3.Cross(v2 - v1, v3 - v1); n1.Normalize(); data[dataIdx] = new CustomVertex.PositionNormalTextured(v1, n1, t1.X, t1.Y); data[dataIdx + 1] = new CustomVertex.PositionNormalTextured(v2, n1, t2.X, t2.Y); data[dataIdx + 2] = new CustomVertex.PositionNormalTextured(v4, n1, t4.X, t4.Y); //Cargar triangulo 2 TGCVector3 n2 = TGCVector3.Cross(v4 - v1, v3 - v1); n2.Normalize(); data[dataIdx + 3] = new CustomVertex.PositionNormalTextured(v1, n2, t1.X, t1.Y); data[dataIdx + 4] = new CustomVertex.PositionNormalTextured(v4, n2, t4.X, t4.Y); data[dataIdx + 5] = new CustomVertex.PositionNormalTextured(v3, n2, t3.X, t3.Y); dataIdx += 6; } } vbTerrain.SetData(data, 0, LockFlags.None); }
public static void CreateVertexBufferFromTriangleList(VertexBuffer vBuffer, ArrayList aryList, object vType) { if(vType is CustomVertex.PositionNormalTextured) { CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[aryList.Count]; int iVertex = 0; foreach(CustomVertex.PositionNormalTextured vVertex in aryList) { verts[iVertex] = vVertex; iVertex++; } vBuffer.SetData(verts, 0, LockFlags.None); } else if(vType is CustomVertex.PositionTextured) { CustomVertex.PositionTextured[] verts = new CustomVertex.PositionTextured[aryList.Count]; int iVertex = 0; foreach(CustomVertex.PositionTextured vVertex in aryList) { verts[iVertex] = vVertex; iVertex++; } vBuffer.SetData(verts, 0, LockFlags.None); } }
/// <returns>An array of PositionNormalTextured vertices</returns> /// <summary> /// Builds an array of PositionNormalTextured vertices that form a /// nX by nY tesselation of a quad given by it's 2 corners /// </summary> /// <param name="bottomLeft">Bottom left corner of the quad</param> /// <param name="topRight">Top right corner of the quad</param> /// <param name="nX">amount of X tesselation</param> /// <param name="nY">amount of Y tesselation</param> /// <param name="texture_bLeft">Texture coordinates for bottom left corner</param> /// <param name="texture_tRight">Texture coordinates for top right corner</param> /// <returns>Array of CustomVertex.PositionNormalTextured vertices</returns> public static CustomVertex.PositionNormalTextured[] BuildPositionNormalTextured(PointF bottomLeft, PointF topRight, int nX, int nY, PointF texture_bLeft, PointF texture_tRight) { if (nX < 2 || nY < 2) { throw new Exception("Cannot tesselate with nX or nY below 2"); } float deltaX = (topRight.X - bottomLeft.X) / (float)(nX - 1); float deltaY = (topRight.Y - bottomLeft.Y) / (float)(nY - 1); float tdeltaX = (texture_tRight.X - texture_bLeft.X) / (float)(nX - 1); float tdeltaY = (texture_tRight.Y - texture_bLeft.Y) / (float)(nY - 1); float fx, fy; float tx, ty; CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[nX * nY]; for (int y = 0; y < nY; y++) { if (y == nY - 1) { fy = topRight.Y; ty = texture_tRight.Y; } else { fy = bottomLeft.Y + (float)y * deltaY; ty = texture_bLeft.Y + (float)y * tdeltaY; } for (int x = 0; x < nX; x++) { if (x == nX - 1) { fx = topRight.X; tx = texture_tRight.Y; } else { fx = bottomLeft.X + (float)x * deltaX; tx = texture_bLeft.X + (float)x * tdeltaX; } verts[y * nY + x].X = fx; verts[y * nY + x].Y = fy; verts[y * nY + x].Z = 0; verts[y * nY + x].Normal = new Vector3(0, 0, -1f); verts[y * nY + x].Tu = tx; verts[y * nY + x].Tv = ty; } } return verts; }
public static void CreateSphereTriangleStrips(Vector3 centre, double radius, int numSegments, out CustomVertex.PositionNormalTextured[] points, out int numStrips, out int vertsPerStrip, out int primsPerStrip) { int numVerts = numSegments * (numSegments / 2) * 3; points = new CustomVertex.PositionNormalTextured[numVerts]; numStrips = numSegments / 2; vertsPerStrip = (numSegments * 2) + 2; primsPerStrip = numSegments * 2; int i, j; double theta1, theta2, theta3; Vector3 e, p; if (radius < 0) radius = -radius; if (numSegments < 0) numSegments = -numSegments; int vIdx = 0; for (j = 0; j < numSegments / 2; j++) { theta1 = j * TWOPI / numSegments - PID2; theta2 = (j + 1) * TWOPI / numSegments - PID2; for (i = 0; i <= numSegments; i++) { theta3 = i * TWOPI / numSegments; e.X = (float)(Math.Cos(theta2) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta2); e.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * (j + 1) / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; e.X = (float)(Math.Cos(theta1) * Math.Cos(theta3)); e.Y = (float)Math.Sin(theta1); e.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3)); p.X = (float)(centre.X + radius * e.X); p.Y = (float)(centre.Y + radius * e.Y); p.Z = (float)(centre.Z + radius * e.Z); points[vIdx].Normal = new Vector3(e.X, e.Y, e.Z); points[vIdx].Tu = (float)(i / (double)numSegments); points[vIdx].Tv = (float)(2 * j / (double)numSegments); points[vIdx].Position = new Vector3(p.X, p.Y, p.Z); vIdx++; } } }
/// <summary> /// Metodo que carga los valores necesarios para inicializar el Oceano. /// </summary> public static void Cargar() { Device d3dDevice = GuiController.Instance.D3dDevice; // Creo la textura de reflexion surf_reflection = new Texture(d3dDevice, GuiController.Instance.Panel3d.Width, GuiController.Instance.Panel3d.Height, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); // Creo la textura de refraccion surf_refraction = new Texture(d3dDevice, GuiController.Instance.Panel3d.Width, GuiController.Instance.Panel3d.Height, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default); // Cargo la textura de fresnel (relación entre los campos eléctricos transmitido y reflejado) "fresnel_water_sRGB.bmp" surf_fresnel = TextureLoader.FromFile(d3dDevice, Utiles.TexturasDir("fresnel_water_sRGB.bmp")); // Carga el shader del movimiento del oceano PerlinShader = Utiles.CargarShaderConTechnique("perlin.fx"); // Cargar informacion de vertices: (X,Y,Z) + coord textura _vertices = new CustomVertex.PositionNormalTextured[CANTIDAD_DE_VERTICES]; int i = 0; for (int x = -RADIO; x <= RADIO; x++) { for (int z = -RADIO; z <= RADIO; z++) { _vertices[i++] = new CustomVertex.PositionNormalTextured( new Vector3(x * DISTANCIA_ENTRE_VERTICES, ParametrosDeConfiguracion.Agua.NivelDelMar, z * DISTANCIA_ENTRE_VERTICES), _normal, ((float)(x + RADIO) / ((float)LARGO - 1)), ((float)(z + RADIO) / ((float)LARGO - 1)) ); } } ; // Creamos el VertexBuffer _vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), CANTIDAD_DE_VERTICES, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default); // Almacenar información en VertexBuffer _vertexBuffer.SetData(_vertices, 0, LockFlags.None); //Creo el quadTree para este terreno QuadTree.Cargar(_pos.X, _pos.Z, TAMAÑO, GuiController.Instance.D3dDevice); // creo los indices para el IndexBuffer usando un array de int // Son por 3 vertices por triangulo y son 2 triangulos for (int z = 0; z < LARGO - 1; z++) { for (int x = 0; x < LARGO - 1; x++) { var lista = new List <int>(); //Primer Triangulo lista.Add(x + z * LARGO); lista.Add(x + 1 + z * LARGO); lista.Add(x + LARGO + 1 + z * LARGO); //Segundo Triangulo lista.Add(x + LARGO + 1 + z * LARGO); lista.Add(x + LARGO + z * LARGO); lista.Add(x + z * LARGO); //Cargo los indices en los nodos del QuadTree QuadTree.AgregarIndices(lista); } } ; //LOD I for (int z = 0; z < LARGO - 1; z = z + 2) { for (int x = 0; x < LARGO - 1; x = x + 2) { var lista = new List <int>(); //Primer Triangulo lista.Add(x + z * LARGO); lista.Add(x + 2 + z * LARGO); lista.Add(x + 2 * LARGO + 2 + z * LARGO); //Segundo Triangulo lista.Add(x + 2 * LARGO + 2 + z * LARGO); lista.Add(x + 2 * LARGO + z * LARGO); lista.Add(x + z * LARGO); //Cargo los indices en los nodos del QuadTree QuadTree.AgregarLODI(lista); } } ; //LOD II for (int z = 0; z < LARGO - 1; z = z + 4) { for (int x = 0; x < LARGO - 1; x = x + 4) { var lista = new List <int>(); //Primer Triangulo lista.Add(x + z * LARGO); lista.Add(x + 4 + z * LARGO); lista.Add(x + 4 * LARGO + 4 + z * LARGO); //Segundo Triangulo lista.Add(x + 4 * LARGO + 4 + z * LARGO); lista.Add(x + 4 * LARGO + z * LARGO); lista.Add(x + z * LARGO); //Cargo los indices en los nodos del QuadTree QuadTree.AgregarLODII(lista); } } ; // Genera los heightmaps entre los que interpola la superficie, se generan para 2,4 y 8 octavas para poder usar // las diferentes configuraciones cambiando los Modifiers. // 2 ocatavas (ruido fuerte). // perlin 1 textPerlinNoise1_2Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 2, out PerlinNoise1_2Octavas); textPerlinNoise2_2Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 2, out PerlinNoise2_2Octavas); // 4 ocatavas (ruido normal). textPerlinNoise1_4Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 4, out PerlinNoise1_4Octavas); textPerlinNoise2_4Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 4, out PerlinNoise2_4Octavas); // 8 octavas (ruido suave). textPerlinNoise1_8Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 8, out PerlinNoise1_8Octavas); textPerlinNoise2_8Octavas = PerlinNoise.GetNuevoHeightmap(Oceano.LARGO, Oceano.LARGO, 8, out PerlinNoise2_8Octavas); // Carga los valores iniciales de la Matriz de Perlin Noise. PerlinNoise1 = PerlinNoise1_8Octavas; PerlinNoise2 = PerlinNoise2_8Octavas; // Carga los valores iniciales de la textura que se usara como Heightmap y Normalmap para la superficie del oceano. textPerlinNoise1 = textPerlinNoise1_8Octavas; textPerlinNoise2 = textPerlinNoise2_8Octavas; // Peso (alpha) para interpolar, usa el InterpoladorVaiven para ir alterandolo. interpoladorPerlinNoiseHeightmaps = new InterpoladorVaiven(); interpoladorPerlinNoiseHeightmaps.Min = 0; interpoladorPerlinNoiseHeightmaps.Max = 1; interpoladorPerlinNoiseHeightmaps.Speed = 0.5f; //guardar el stencil inicial //g_depthstencil = d3dDevice.DepthStencilSurface; }
/// <summary> /// Generates a mesh from the parsed /// information of the file /// </summary> private void GenerateMesh(Device d3dDevice) { if(m_alNormals.Count == 0) throw new System.Exception("No normals were found for this mesh."); if(m_intNumFaces == 0) throw new System.Exception("No faces were found for this mesh."); if(m_intNumVerts == 0) throw new System.Exception("No vertices were found for this mesh."); //create a mesh with Poisiton, Normal, and Texture info. Even if it doesn't contain TextCoords m_d3dMesh = new Mesh(m_intNumFaces, m_intNumVerts, MeshFlags.Managed, CustomVertex.PositionNormalTextured.Format, d3dDevice); //index array short[] aryIndices = new short[m_alVertFormat.Count]; CustomVertex.PositionNormalTextured[] aryVerts = new CustomVertex.PositionNormalTextured[m_intNumVerts]; Vector3 v, t, n; CustomVertex.PositionNormalTextured cvVert; //loop through each face and apply the format for(int i=0; i<m_intNumFaces * 3; i++) { //parse the vertex information string[] aryVertInfo = (string[])m_alVertFormat[i]; //first one is vertex index short index = short.Parse(aryVertInfo[0]); //OBJ format starts at 1 not 0 index--; //set the index arry aryIndices[i] = index; v = (Vector3)m_alVertices[index]; t = new Vector3(0,0,0); //parse the texture coords if( aryVertInfo.Length == 3) { index = short.Parse(aryVertInfo[1]); index--; //set the texture coordinate t = (Vector3)m_alTextCoords[index]; index = short.Parse(aryVertInfo[2]); index--; //set the normal n = (Vector3)m_alNormals[index]; } else { index = short.Parse(aryVertInfo[1]); index--; //set the normal n = (Vector3)m_alNormals[index]; } cvVert = aryVerts[aryIndices[i]]; cvVert.Position = v; cvVert.Normal = n; cvVert.Tu = t.X; cvVert.Tv = t.Y; aryVerts[aryIndices[i]] = cvVert; }//end for loop m_d3dMesh.VertexBuffer.SetData(aryVerts,0, LockFlags.None); m_d3dMesh.IndexBuffer.SetData(aryIndices,0,LockFlags.None); AttributeRange ar = new AttributeRange(); ar.AttributeId = 0; ar.FaceCount = m_intNumFaces; ar.FaceStart = 0; ar.VertexCount = m_intNumVerts; ar.VertexStart = 0; m_d3dMesh.SetAttributeTable(new AttributeRange[] {ar}); int[] adj = new int[m_intNumFaces * 3]; m_d3dMesh.GenerateAdjacency(0.01f, adj); m_d3dMesh.OptimizeInPlace(MeshFlags.OptimizeVertexCache | MeshFlags.OptimizeIgnoreVerts, adj); m_d3dMesh.ComputeNormals(); m_bLoaded = true; }
private void RebuildAsync(Object deviceObj) { try { Device device = (Device)deviceObj; // Rebuild if (_bitmap == null) { _bitmap = new Bitmap(1, 1); _valid = true; } else { try { _imageTexture = Texture.FromBitmap(device, _bitmap, Usage.Dynamic, Pool.Default); // Set up the material _imageMaterial = new Material(); _imageMaterial.Diffuse = _color; // Set up the rectangular mesh CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[4]; verts[0].Position = new Vector3(0, 0, -_height); verts[0].Normal = new Vector3(0, 1, 0); verts[0].Tu = 0; verts[0].Tv = 1; verts[1].Position = new Vector3(_width, 0, -_height); verts[1].Normal = new Vector3(0, 1, 0); verts[1].Tu = 1; verts[1].Tv = 1; verts[2].Position = new Vector3(_width, 0, 0); verts[2].Normal = new Vector3(0, 1, 0); verts[2].Tu = 1; verts[2].Tv = 0; verts[3].Position = new Vector3(0, 0, 0); verts[3].Normal = new Vector3(0, 1, 0); verts[3].Tu = 0; verts[3].Tv = 0; AttributeRange[] attributes = new AttributeRange[1]; attributes[0].AttributeId = 0; attributes[0].FaceCount = 2; attributes[0].FaceStart = 0; attributes[0].VertexCount = 4; attributes[0].VertexStart = 0; short[] indices = new short[] { 0, 1, 2, 0, 2, 3 }; _imageSprite = new Mesh(2, 4, 0, CustomVertex.PositionNormalTextured.Format, device); _imageSprite.SetVertexBufferData(verts, LockFlags.Discard); _imageSprite.SetIndexBufferData(indices, LockFlags.Discard); _imageSprite.SetAttributeTable(attributes); _valid = true; } catch (Exception) { _valid = false; _imageTexture = null; _imageSprite = null; return; } } } catch (Exception) { _valid = false; _imageTexture = null; _imageSprite = null; } finally { _building = false; } }
public FedeSkybox(string path, float epsilon) { var corner0 = new Vector3(1, -1, -1); var corner1 = new Vector3(-1, -1, -1); var corner2 = new Vector3(1, 1, -1); var corner3 = new Vector3(-1, 1, -1); var corner4 = new Vector3(1, -1, 1); var corner5 = new Vector3(-1, -1, 1); var corner6 = new Vector3(1, 1, 1); var corner7 = new Vector3(-1, 1, 1); var normal0 = Vector3.Normalize(-corner0); var normal1 = Vector3.Normalize(-corner1); var normal2 = Vector3.Normalize(-corner2); var normal3 = Vector3.Normalize(-corner3); var normal4 = Vector3.Normalize(-corner4); var normal5 = Vector3.Normalize(-corner5); var normal6 = Vector3.Normalize(-corner6); var normal7 = Vector3.Normalize(-corner7); vertexBuffer = new CustomVertex.PositionNormalTextured[36]; float x0 = 0 + epsilon, x1 = 0.25f + epsilon, x2 = 0.5f - epsilon, x3 = 0.75f, x4 = 1 - epsilon; float y0 = 0 + epsilon, y1 = 1 / 3f + epsilon, y2 = 2 / 3f - epsilon, y3 = 1 - epsilon; // Front vertexBuffer[0] = new CustomVertex.PositionNormalTextured(corner0, normal0, x1, y2); vertexBuffer[1] = new CustomVertex.PositionNormalTextured(corner1, normal1, x2, y2); vertexBuffer[2] = new CustomVertex.PositionNormalTextured(corner2, normal2, x1, y1); vertexBuffer[3] = new CustomVertex.PositionNormalTextured(corner1, normal1, x2, y2); vertexBuffer[4] = new CustomVertex.PositionNormalTextured(corner2, normal2, x1, y1); vertexBuffer[5] = new CustomVertex.PositionNormalTextured(corner3, normal3, x2, y1); // Top vertexBuffer[6] = new CustomVertex.PositionNormalTextured(corner2, normal2, x1, y1); vertexBuffer[7] = new CustomVertex.PositionNormalTextured(corner3, normal3, x2, y1); vertexBuffer[8] = new CustomVertex.PositionNormalTextured(corner7, normal7, x2, y0); vertexBuffer[9] = new CustomVertex.PositionNormalTextured(corner2, normal2, x1, y1); vertexBuffer[10] = new CustomVertex.PositionNormalTextured(corner6, normal6, x1, y0); vertexBuffer[11] = new CustomVertex.PositionNormalTextured(corner7, normal7, x2, y0); // Right vertexBuffer[12] = new CustomVertex.PositionNormalTextured(corner1, normal1, x2, y2); vertexBuffer[13] = new CustomVertex.PositionNormalTextured(corner3, normal3, x2, y1); vertexBuffer[14] = new CustomVertex.PositionNormalTextured(corner7, normal7, x3, y1); vertexBuffer[15] = new CustomVertex.PositionNormalTextured(corner1, normal1, x2, y2); vertexBuffer[16] = new CustomVertex.PositionNormalTextured(corner5, normal5, x3, y2); vertexBuffer[17] = new CustomVertex.PositionNormalTextured(corner7, normal7, x3, y1); //Left vertexBuffer[18] = new CustomVertex.PositionNormalTextured(corner4, normal4, x0, y2); vertexBuffer[19] = new CustomVertex.PositionNormalTextured(corner6, normal6, x0, y1); vertexBuffer[20] = new CustomVertex.PositionNormalTextured(corner2, normal2, x1, y1); vertexBuffer[21] = new CustomVertex.PositionNormalTextured(corner4, normal4, x0, y2); vertexBuffer[22] = new CustomVertex.PositionNormalTextured(corner0, normal0, x1, y2); vertexBuffer[23] = new CustomVertex.PositionNormalTextured(corner2, normal2, x1, y1); //Down vertexBuffer[24] = new CustomVertex.PositionNormalTextured(corner1, normal1, x2, y2); vertexBuffer[25] = new CustomVertex.PositionNormalTextured(corner4, normal4, x1, y3); vertexBuffer[26] = new CustomVertex.PositionNormalTextured(corner5, normal5, x2, y3); vertexBuffer[27] = new CustomVertex.PositionNormalTextured(corner0, normal0, x1, y2); vertexBuffer[28] = new CustomVertex.PositionNormalTextured(corner1, normal1, x2, y2); vertexBuffer[29] = new CustomVertex.PositionNormalTextured(corner4, normal4, x1, y3); //Back vertexBuffer[30] = new CustomVertex.PositionNormalTextured(corner4, normal4, x4, y2); vertexBuffer[31] = new CustomVertex.PositionNormalTextured(corner5, normal5, x3, y2); vertexBuffer[32] = new CustomVertex.PositionNormalTextured(corner7, normal7, x3, y1); vertexBuffer[33] = new CustomVertex.PositionNormalTextured(corner4, normal4, x4, y2); vertexBuffer[34] = new CustomVertex.PositionNormalTextured(corner6, normal6, x4, y1); vertexBuffer[35] = new CustomVertex.PositionNormalTextured(corner7, normal7, x3, y1); //texture = TextureLoader.FromFile(D3DDevice.Instance.Device, Game.Default.MediaDirectory + "Daylight-Box-UV.png"); //texture = TextureRepository.SkyboxOutside; texture = TextureLoader.FromFile(D3DDevice.Instance.Device, Game.Default.MediaDirectory + path); }
public void ReCreateBuffer(Device device, Grid2D grid) { Point p1 = grid.ConvertGlobalCoordsToLocal(rectFront.Location); localRectFront = new Rectangle(p1, new Size(w, h)); p1 = grid.ConvertGlobalCoordsToLocal(rectRight.Location); localRectRight = new Rectangle(p1, new Size(w, h)); p1 = grid.ConvertGlobalCoordsToLocal(rectTop.Location); localRectTop = new Rectangle(p1, new Size(w, w)); CustomVertex.PositionNormalTextured[] vertex = new CustomVertex.PositionNormalTextured[36]; #region FrontSide vertex[0] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y, localRectTop.Y - localRectTop.Height, 0, 0, -1, 0, 0); vertex[1] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y - localRectTop.Height, 0, 0, -1, 1, 0); vertex[2] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, 0, 0, -1, 1, 1); vertex[3] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y, localRectTop.Y - localRectTop.Height, 0, 0, -1, 0, 0); vertex[4] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, 0, 0, -1, 1, 1); vertex[5] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, 0, 0, -1, 0, 1); #endregion #region RightSide vertex[6] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y - localRectTop.Height, 1, 0, 0, 0, 0); vertex[7] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectRight.Y, localRectTop.Y, 1, 0, 0, 1, 0); vertex[8] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectRight.Y - localRectRight.Height, localRectTop.Y, 1, 0, 0, 1, 1); vertex[9] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y - localRectTop.Height, 1, 0, 0, 0, 0); vertex[10] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectRight.Y - localRectRight.Height, localRectTop.Y, 1, 0, 0, 1, 1); vertex[11] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectRight.Y - localRectRight.Height, localRectTop.Y - localRectTop.Height, 1, 0, 0, 0, 1); #endregion #region BackSide vertex[12] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y, 0, 0, 1, 0, 0); vertex[13] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectRight.Y, localRectTop.Y, 0, 0, 1, 1, 0); vertex[14] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectRight.Y - localRectRight.Height, localRectTop.Y, 0, 0, 1, 1, 1); vertex[15] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y, 0, 0, 1, 0, 0); vertex[16] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectRight.Y - localRectRight.Height, localRectTop.Y, 0, 0, 1, 1, 1); vertex[17] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectRight.Y - localRectRight.Height, localRectTop.Y, 0, 0, 1, 0, 1); #endregion #region LeftSide vertex[18] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y, localRectTop.Y, -1, 0, 0, 0, 0); vertex[19] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y, localRectTop.Y - localRectTop.Height, -1, 0, 0, 1, 0); vertex[20] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, -1, 0, 0, 1, 1); vertex[21] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y, localRectTop.Y, -1, 0, 0, 0, 0); vertex[22] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, -1, 0, 0, 1, 1); vertex[23] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y - localRectFront.Height, localRectTop.Y, -1, 0, 0, 0, 1); #endregion #region Upside vertex[24] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectRight.Y, localRectTop.Y, 0, 1, 0, 0, 0); vertex[25] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y, 0, 1, 0, 1, 0); vertex[26] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y - localRectTop.Height, 0, 1, 0, 1, 1); vertex[27] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectRight.Y, localRectTop.Y, 0, 1, 0, 0, 0); vertex[28] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y, localRectTop.Y - localRectTop.Height, 0, 1, 0, 1, 1); vertex[29] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y, localRectTop.Y - localRectTop.Height, 0, 1, 0, 0, 1); #endregion #region DownSide vertex[30] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, 0, -1, 0, 0, 0); vertex[31] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, 0, -1, 0, 1, 0); vertex[32] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y - localRectFront.Height, localRectTop.Y, 0, -1, 0, 1, 1); vertex[33] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y - localRectFront.Height, localRectTop.Y - localRectTop.Height, 0, -1, 0, 0, 0); vertex[34] = new CustomVertex.PositionNormalTextured(localRectFront.X + localRectFront.Width, localRectFront.Y - localRectFront.Height, localRectTop.Y, 0, -1, 0, 1, 1); vertex[35] = new CustomVertex.PositionNormalTextured(localRectFront.X, localRectFront.Y - localRectFront.Height, localRectTop.Y, 0, -1, 0, 0, 1); #endregion cv_PnTex = vertex; vBuf = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 36, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default); vBuf.SetData(vertex, 0, LockFlags.None); }
public static Mesh CreateBox(Microsoft.DirectX.Direct3D.Device d3dDevice, float fltX, float fltY, float fltZ) { //VertexBuffer vb = (VertexBuffer)sender; ArrayList aryStrips = new ArrayList(); ArrayList aryTriangleList; CustomVertex.PositionNormalTextured[] verts; Microsoft.DirectX.Vector3 vNormal = new Vector3(); verts = new CustomVertex.PositionNormalTextured[4]; vNormal.X = 0; vNormal.Y = 1; vNormal.Z = 0; verts[0] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 0); verts[1] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 1); verts[2] = new CustomVertex.PositionNormalTextured( fltX*0.5f, fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 0); verts[3] = new CustomVertex.PositionNormalTextured( fltX*0.5f, fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 1); aryStrips.Add(verts); verts = new CustomVertex.PositionNormalTextured[4]; vNormal.X = 0; vNormal.Y = -1; vNormal.Z = 0; verts[0] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, -fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 0); verts[1] = new CustomVertex.PositionNormalTextured( fltX*0.5f, -fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 1); verts[2] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, -fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 0); verts[3] = new CustomVertex.PositionNormalTextured( fltX*0.5f, -fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 1); aryStrips.Add(verts); verts = new CustomVertex.PositionNormalTextured[4]; vNormal.X = 1; vNormal.Y = 0; vNormal.Z = 0; verts[0] = new CustomVertex.PositionNormalTextured( fltX*0.5f, -fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 0); verts[1] = new CustomVertex.PositionNormalTextured( fltX*0.5f, fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 1); verts[2] = new CustomVertex.PositionNormalTextured( fltX*0.5f, -fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 0); verts[3] = new CustomVertex.PositionNormalTextured( fltX*0.5f, fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 1); aryStrips.Add(verts); verts = new CustomVertex.PositionNormalTextured[4]; vNormal.X = -1; vNormal.Y = 0; vNormal.Z = 0; verts[0] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, -fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 0); verts[1] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, -fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 1); verts[2] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 0); verts[3] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 1); aryStrips.Add(verts); verts = new CustomVertex.PositionNormalTextured[4]; vNormal.X = 0; vNormal.Y = 0; vNormal.Z = 1; verts[0] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, -fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 0); verts[1] = new CustomVertex.PositionNormalTextured( fltX*0.5f, -fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 1); verts[2] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 0); verts[3] = new CustomVertex.PositionNormalTextured( fltX*0.5f, fltY*0.5f, fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 1); aryStrips.Add(verts); verts = new CustomVertex.PositionNormalTextured[4]; vNormal.X = 0; vNormal.Y = 0; vNormal.Z = -1; verts[0] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, -fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 0); verts[1] = new CustomVertex.PositionNormalTextured(-fltX*0.5f, fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 0, 1); verts[2] = new CustomVertex.PositionNormalTextured( fltX*0.5f, -fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 0); verts[3] = new CustomVertex.PositionNormalTextured( fltX*0.5f, fltY*0.5f, -fltZ*0.5f, vNormal.X, vNormal.Y, vNormal.Z, 1, 1); aryStrips.Add(verts); aryTriangleList = ConvertTriStripToTriList(aryStrips, true); return CreateMeshFromTriangleList(d3dDevice, aryTriangleList); }
private void OnVertexBufferCreate(object sender, EventArgs e) { VertexBuffer buffer = (VertexBuffer)sender; CustomVertex.PositionNormalTextured[] verts_triangle = new CustomVertex.PositionNormalTextured[6]; verts_triangle[0] = new CustomVertex.PositionNormalTextured(512.0f, 0.0f, 512.0f, 0.0f, 4000.0f, 0.0f, 0.0f, 1.0f); verts_triangle[1] = new CustomVertex.PositionNormalTextured(512.0f, 0.0f, -512.0f, 0.0f, 4000.0f, 0.0f, 0.0f, 0.0f); verts_triangle[2] = new CustomVertex.PositionNormalTextured(-512.0f, 0.0f, -512.0f, 0.0f, 4000.0f, 0.0f, 1.0f, 0.0f); verts_triangle[3] = new CustomVertex.PositionNormalTextured(-512.0f, 0.0f, -512.0f, 0.0f, 4000.0f, 0.0f, 1.0f, 0.0f); verts_triangle[4] = new CustomVertex.PositionNormalTextured(-512.0f, 0.0f, 512.0f, 0.0f, 4000.0f, 0.0f, 1.0f, 1.0f); verts_triangle[5] = new CustomVertex.PositionNormalTextured(512.0f, 0.0f, 512.0f, 0.0f, 4000.0f, 0.0f, 0.0f, 1.0f); buffer.SetData(verts_triangle, 0, LockFlags.None); }
public static Mesh CreateSphere(Microsoft.DirectX.Direct3D.Device d3dDevice, float fltRadius, int iRings, int iSides) { CustomVertex.PositionNormalTextured[] verts; ArrayList aryStrips = new ArrayList(); ArrayList aryTriangleList; //initialize the strips for(int iStrip=0; iStrip<iRings; iStrip++) aryStrips.Add(new CustomVertex.PositionNormalTextured[2*(iSides+1)]); //Initialize the rings. Vector3[] aryVertices = new Vector3[iRings+1]; Vector3[] aryNormals = new Vector3[iRings+1]; float[] aryCoords = new float[iRings+1]; for(int iRing=0; iRing<iRings+1; iRing++) { float fltAngle = ((float)iRing/iRings) * (float) Math.PI; aryNormals[iRing] = new Vector3(0, (float) Math.Sin(fltAngle), (float) Math.Cos(fltAngle)); aryVertices[iRing] = new Vector3(aryNormals[iRing].X*fltRadius, aryNormals[iRing].Y*fltRadius, aryNormals[iRing].Z*fltRadius); aryCoords[iRing] = ((float)iRing/iRings); } /* Then transform that arc to each angle. */ Vector3 vVertex, vNormal; float fltU, fltV; for(int iSide=0; iSide<iSides+1; iSide++) { float fltAroundAngle = ((float)iSide/iSides) * 2 * (float) Math.PI; Microsoft.DirectX.Matrix mR = Matrix3MakeRotationZ(fltAroundAngle); for(int iRing=0; iRing<iRings; iRing++) { verts = (CustomVertex.PositionNormalTextured[]) aryStrips[iRing]; vVertex = Matrix3MultiplyVector(mR, aryVertices[iRing]); vNormal = Matrix3MultiplyVector(mR, aryNormals[iRing]); fltU = ((float)iSide/iSides); fltV = aryCoords[iRing]; verts[iSide*2] = new CustomVertex.PositionNormalTextured(vVertex.X, vVertex.Y, vVertex.Z, vNormal.X, vNormal.Y, vNormal.Z, fltU, fltV); vVertex = Matrix3MultiplyVector(mR, aryVertices[iRing+1]); vNormal = Matrix3MultiplyVector(mR, aryNormals[iRing+1]); fltU = ((float)iSide/iSides); fltV = aryCoords[iRing+1]; verts[(iSide*2)+1] = new CustomVertex.PositionNormalTextured(vVertex.X, vVertex.Y, vVertex.Z, vNormal.X, vNormal.Y, vNormal.Z, fltU, fltV); } } aryTriangleList = ConvertTriStripToTriList(aryStrips, false); return CreateMeshFromTriangleList(d3dDevice, aryTriangleList); }
private Mesh CreateMesh(aiMesh aiMesh, out Vector3 min, out Vector3 max) { var numFaces = (int) aiMesh.mNumFaces; var numVertices = (int) aiMesh.mNumVertices; var dxMesh = new Mesh(numFaces, numVertices, MeshFlags.Managed | MeshFlags.Use32Bit, CustomVertex.PositionNormalTextured.Format, device); var aiPositions = aiMesh.mVertices; var aiNormals = aiMesh.mNormals; var aiTextureCoordsAll = aiMesh.mTextureCoords; var aiTextureCoords = (aiTextureCoordsAll!=null) ? aiTextureCoordsAll[0] : null; var dxVertices = new CustomVertex.PositionNormalTextured[numVertices]; for (int i = 0; i < numVertices; ++i) { dxVertices[i].Position = aiPositions[i].ToVector3(); if (aiNormals != null) { dxVertices[i].Normal = aiNormals[i].ToVector3(); } if (aiTextureCoords != null) { var uv = aiTextureCoords[i]; dxVertices[i].Tu = uv.x; dxVertices[i].Tv = uv.y; } } dxMesh.VertexBuffer.SetData(dxVertices, 0, LockFlags.None); var aiFaces = aiMesh.mFaces; var dxIndices = new uint[numFaces * 3]; for (int i = 0; i < numFaces; ++i) { var aiFace = aiFaces[i]; var aiIndices = aiFace.mIndices; for (int j = 0; j < 3; ++j) { dxIndices[i * 3 + j] = aiIndices[j]; } } dxMesh.IndexBuffer.SetData(dxIndices, 0, LockFlags.None); var dxAttributes = dxMesh.LockAttributeBufferArray(LockFlags.None); // TODO: Set face material index for attributes dxMesh.UnlockAttributeBuffer(dxAttributes); var adjacency = new int[numFaces * 3]; dxMesh.GenerateAdjacency(0.0f, adjacency); dxMesh.OptimizeInPlace(MeshFlags.OptimizeAttributeSort, adjacency); Geometry.ComputeBoundingBox(dxVertices, CustomVertex.PositionNormalTextured.StrideSize, out min, out max); return dxMesh; }
private void crearVertices() { int i = 0; int b = 0; for (int z = 0; z < DIMENSION; z++) { for (int x = 0; x < DIMENSION; x++) { /*Cuadrado * 1--4 | | | 2--3 */ //vertice 1 VerticeAgua v1 = vertices[x, z]; //vertice 2 VerticeAgua v2 = vertices[x, z + 1]; //vertice 3 VerticeAgua v3 = vertices[x + 1, z + 1]; //vertice 4 VerticeAgua v4 = vertices[x + 1, z]; //vertice 1 Vector3 n1 = Vector3.Cross(v1.Pos - v2.Pos, v1.Pos - v4.Pos); //Vector3 n1 = Vector3.Cross(v2.Pos - v1.Pos, v4.Pos-v1.Pos); //normals.Add(TgcArrow.fromDirection(v1.Pos, Vector3.Scale(n1, 10f))); n1.Normalize(); //Vector3 n1 = new Vector3(0, 1, 0); data[i + 0] = new CustomVertex.PositionNormalTextured(v1.Pos, n1, v1.UV.X, v1.UV.Y); //vertice 2 Vector3 n2 = Vector3.Cross(v2.Pos - v3.Pos, v2.Pos - v1.Pos); //Vector3 n2 = Vector3.Cross(v3.Pos - v2.Pos, v1.Pos - v2.Pos); //normals.Add(TgcArrow.fromDirection(v2.Pos, Vector3.Scale(n2, 10f))); n2.Normalize(); //Vector3 n2 = new Vector3(0, 1, 0); data[i + 1] = new CustomVertex.PositionNormalTextured(v2.Pos, n2, v2.UV.X, v2.UV.Y); //vertice 3 Vector3 n3 = Vector3.Cross(v3.Pos - v4.Pos, v3.Pos - v2.Pos); //Vector3 n3 = Vector3.Cross(v4.Pos - v3.Pos, v2.Pos - v3.Pos); //normals.Add(TgcArrow.fromDirection(v3.Pos, Vector3.Scale(n3, 10f))); n3.Normalize(); //Vector3 n3 = new Vector3(0,1,0); data[i + 2] = new CustomVertex.PositionNormalTextured(v3.Pos, n3, v3.UV.X, v3.UV.Y); //vertice 4 Vector3 n4 = Vector3.Cross(v4.Pos - v1.Pos, v4.Pos - v3.Pos); //Vector3 n4 = Vector3.Cross(v1.Pos - v4.Pos, v3.Pos - v4.Pos); //normals.Add(TgcArrow.fromDirection(v4.Pos, Vector3.Scale(n4, 10f))); n4.Normalize(); //Vector3 n4 = new Vector3(0,1,0); data[i + 3] = new CustomVertex.PositionNormalTextured(v4.Pos, n4, v4.UV.X, v4.UV.Y); //Buffer indice[b + 0] = i + 0; indice[b + 1] = i + 1; indice[b + 2] = i + 2; indice[b + 3] = i + 3; indice[b + 4] = i + 0; indice[b + 5] = i + 2; i += 4; b += 6; } } }
/// <summary> /// Creates a PositionNormalTextured sphere centered on zero /// </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 TexturedSphere(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.PositionNormalTextured.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.PositionNormalTextured), 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.PositionNormalTextured pnt = new CustomVertex.PositionNormalTextured(); double longitude = 180 - ((float)slice / slices * (float)360); Point3d v = MathEngine.SphericalToCartesian(latitude, longitude, radius); pnt.X = (float)v.X; pnt.Y = (float)v.Y; pnt.Z = (float)v.Z; pnt.Tu = 1.0f - (float)slice / slices; pnt.Tv = 1.0f - (float)stack / stacks; 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++); // outside text. arr.SetValue((short)(topVertex + 1), i++); // outside text. arr.SetValue(bottomVertex, i++); arr.SetValue((short)(topVertex + 1), i++); // outside text. arr.SetValue((short)(bottomVertex + 1), i++); // outside text. bottomVertex++; topVertex++; } } mesh.IndexBuffer.SetData(arr, 0, LockFlags.None); mesh.IndexBuffer.Unlock(); mesh.ComputeNormals(); return(mesh); }
public void OnCreateVBMinimap(object sender, EventArgs e) { var buffer = sender as VertexBuffer; CustomVertex.PositionNormalTextured[] texturedArray = (CustomVertex.PositionNormalTextured[])buffer.Lock(0, LockFlags.None); Microsoft.DirectX.Vector3 vector = new Microsoft.DirectX.Vector3(-(this.tileSize / 2f), -(this.tileSize / 2f), 0f); Microsoft.DirectX.Vector3 vector2 = new Microsoft.DirectX.Vector3(this.tileSize / 2f, -(this.tileSize / 2f), 0f); Microsoft.DirectX.Vector3 vector3 = new Microsoft.DirectX.Vector3(-(this.tileSize / 2f), this.tileSize / 2f, 0f); Microsoft.DirectX.Vector3 nor = this.ComputeNormal(vector, vector2, vector3); texturedArray[0] = new CustomVertex.PositionNormalTextured(vector, nor, 0f, 0f); texturedArray[1] = new CustomVertex.PositionNormalTextured(vector2, nor, 1f, 0f); texturedArray[2] = new CustomVertex.PositionNormalTextured(vector3, nor, 0f, 1f); vector = new Microsoft.DirectX.Vector3(this.tileSize / 2f, this.tileSize / 2f, 0f); vector2 = new Microsoft.DirectX.Vector3(-(this.tileSize / 2f), this.tileSize / 2f, 0f); vector3 = new Microsoft.DirectX.Vector3(this.tileSize / 2f, -(this.tileSize / 2f), 0f); nor = this.ComputeNormal(vector, vector2, vector3); texturedArray[3] = new CustomVertex.PositionNormalTextured(vector, nor, 1f, 1f); texturedArray[4] = new CustomVertex.PositionNormalTextured(vector2, nor, 0f, 1f); texturedArray[5] = new CustomVertex.PositionNormalTextured(vector3, nor, 1f, 0f); buffer.Unlock(); }