/// <summary> /// Fill the trees vertex buffer /// </summary> void CreateTreeData(object sender, EventArgs e) { VertexBuffer vb = (VertexBuffer)sender; //Each tree has 4 vertices CustomVertex.PositionColoredTextured[] v = new CustomVertex.PositionColoredTextured[numberTrees * 4]; // Load the vertex data for each tree into a large vertex buffer int iTree; int offsetIndex = 0; for (iTree = 0; iTree < numberTrees; iTree++) { v[offsetIndex + 0] = ((Tree)trees[iTree]).V0; v[offsetIndex + 1] = ((Tree)trees[iTree]).V1; v[offsetIndex + 2] = ((Tree)trees[iTree]).V2; v[offsetIndex + 3] = ((Tree)trees[iTree]).V3; Tree t = (Tree)trees[iTree]; t.OffsetIndex = offsetIndex; trees[iTree] = t; offsetIndex += 4; } vb.SetData(v, 0, 0); }
public override void Generate(ref Device device) { bounds = new System.Drawing.RectangleF(-30.0f, 0.0f, 60.0f, 30.0f); texture = Microsoft.DirectX.Direct3D.TextureLoader.FromFile( device, Environment.CurrentDirectory + "\\Texture\\SKY_BOX_EGYPT.BMP", 0, 0, 1, Usage.None, Format.Unknown, Pool.Managed, Filter.None, Filter.None, System.Drawing.Color.Magenta.ToArgb()); float yOffSet = bounds.Height / 2; vertices = new CustomVertex.PositionColoredTextured[4]; vertices[0].Position = new Vector3(bounds.X, bounds.Y + yOffSet, -15.0f); vertices[0].Tu = 0.0f; vertices[0].Tv = 0.0f; vertices[0].Color = System.Drawing.Color.LightBlue.ToArgb(); vertices[1].Position = new Vector3(bounds.X, bounds.Y - yOffSet, -15.0f); vertices[1].Color = System.Drawing.Color.White.ToArgb(); vertices[1].Tu = 0.0f; vertices[1].Tv = 1.0f; vertices[2].Position = new Vector3(bounds.X + bounds.Width, bounds.Y + yOffSet, -15.0f); vertices[2].Color = System.Drawing.Color.LightBlue.ToArgb(); vertices[2].Tu = 1.0f; vertices[2].Tv = 0.0f; vertices[3].Position = new Vector3(bounds.X + bounds.Width, bounds.Y - yOffSet, -15.0f); vertices[3].Color = System.Drawing.Color.White.ToArgb(); vertices[3].Tu = 1.0f; vertices[3].Tv = 1.0f; }
private CustomVertex.PositionColoredTextured[] CreateMesh(int meshPointCount) { int upperBound = meshPointCount - 1; float scaleFactor = (float)1 / upperBound; double latrange = this.North - this.South; double lonrange = this.East - this.West; m_nVertices = meshPointCount * meshPointCount; CustomVertex.PositionColoredTextured[] vertices = new CustomVertex.PositionColoredTextured[meshPointCount * meshPointCount]; for (int i = 0; i < meshPointCount; i++) { for (int j = 0; j < meshPointCount; j++) { Vector3 pos = SMath.SphericalToCartesian( this.North - scaleFactor * latrange * i, this.West + scaleFactor * lonrange * j, m_fRadius); vertices[i * meshPointCount + j].X = pos.X; vertices[i * meshPointCount + j].Y = pos.Y; vertices[i * meshPointCount + j].Z = pos.Z; vertices[i * meshPointCount + j].Tu = (float)j / meshPointCount; vertices[i * meshPointCount + j].Tv = (float)i / meshPointCount; } } return(vertices); }
private Mesh Rectangle(float width, float height) { Mesh outMesh = new Mesh(2, 6, MeshFlags.Managed, CustomVertex.PositionColoredTextured.Format, device); CustomVertex.PositionColoredTextured[] points = new CustomVertex.PositionColoredTextured[4]; short [] curIndices = new short[6]; int cl = Color.FromArgb(230, 230, 230).ToArgb(); points[0] = new CustomVertex.PositionColoredTextured(new Vector3(-width / 2, 0, -height / 2), cl, 0, 1); points[1] = new CustomVertex.PositionColoredTextured(new Vector3(-width / 2, 0, height / 2), cl, 0, 0); points[2] = new CustomVertex.PositionColoredTextured(new Vector3(width / 2, 0, height / 2), cl, 1, 0); points[3] = new CustomVertex.PositionColoredTextured(new Vector3(width / 2, 0, -height / 2), cl, 1, 1); curIndices [0] = 0; curIndices [1] = 1; curIndices [2] = 2; curIndices [3] = 0; curIndices [4] = 2; curIndices [5] = 3; outMesh.SetVertexBufferData(points, LockFlags.None); outMesh.SetIndexBufferData(curIndices, LockFlags.None); return(outMesh); }
/// <summary> /// Updates the vertex buffer to be a quad with 1pt in width/height and with the pivot in the center of it /// </summary> /// <param name="vertexBuffer">Vertex Buffer to update</param> /// <param name="colorKey">Color Key to apply to the buffer</param> protected void UpdateBufferData(VertexBuffer vertexBuffer, Color colorKey) { int color = colorKey.ToArgb(); try { Microsoft.DirectX.GraphicsStream stm = vertexBuffer.Lock(0, 0, 0); CustomVertex.PositionColoredTextured[] verts = (CustomVertex.PositionColoredTextured[])vertexBuffer.Lock(0, LockFlags.Discard); // Bottom left verts[0] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( -0.5f, 0.5f, 0), color, 0.0f, 1.0f); // Top left verts[1] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( -0.5f, -0.5f, 0), color, 0.0f, 0.0f); // Bottom right verts[2] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( 0.5f, 0.5f, 0), color, 1.0f, 1.0f); // Top right verts[3] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( 0.5f, -0.5f, 0), color, 1.0f, 0.0f); stm.Write(verts); vertexBuffer.Unlock(); } catch (Exception) { try { vertexBuffer.Unlock(); } catch (Exception) {} } }
/// <summary> /// Crea los vertices /// </summary> private void loadVertices() { var dataIdx = 0; float width = HeightmapData.GetLength(0); float length = HeightmapData.GetLength(1); var color = Color.White.ToArgb(); vertices = new CustomVertex.PositionColoredTextured[TotalVertices]; maxIntensity = 0; minIntensity = -1; for (var i = 0; i < width - 1; i++) { for (var j = 0; j < length - 1; j++) { if (HeightmapData[i, j] > maxIntensity) { maxIntensity = HeightmapData[i, j]; } if (minIntensity == -1 || HeightmapData[i, j] < minIntensity) { minIntensity = HeightmapData[i, j]; } //Vertices var v1 = new TGCVector3(i, HeightmapData[i, j], j); var v2 = new TGCVector3(i, HeightmapData[i, j + 1], j + 1); var v3 = new TGCVector3(i + 1, HeightmapData[i + 1, j], j); var v4 = new TGCVector3(i + 1, HeightmapData[i + 1, j + 1], j + 1); //Coordendas de textura var t1 = new TGCVector2(i / width, j / length); var t2 = new TGCVector2(i / width, (j + 1) / length); var t3 = new TGCVector2((i + 1) / width, j / length); var t4 = new TGCVector2((i + 1) / width, (j + 1) / length); //Cargar triangulo 1 vertices[dataIdx] = new CustomVertex.PositionColoredTextured(v1, color, t1.X, t1.Y); vertices[dataIdx + 1] = new CustomVertex.PositionColoredTextured(v2, color, t2.X, t2.Y); vertices[dataIdx + 2] = new CustomVertex.PositionColoredTextured(v4, color, t4.X, t4.Y); //Cargar triangulo 2 vertices[dataIdx + 3] = new CustomVertex.PositionColoredTextured(v1, color, t1.X, t1.Y); vertices[dataIdx + 4] = new CustomVertex.PositionColoredTextured(v4, color, t4.X, t4.Y); vertices[dataIdx + 5] = new CustomVertex.PositionColoredTextured(v3, color, t3.X, t3.Y); dataIdx += 6; } vbTerrain.SetData(vertices, 0, LockFlags.None); aabb.setExtremes(new TGCVector3(0, minIntensity, 0), new TGCVector3(HeightmapData.GetLength(0), maxIntensity, HeightmapData.GetLength(1))); } }
private void updateDraw() { //vectores utilizados para el dibujado var upVector = TGCVector3.Up; var n = new TGCVector3(1, 0, 0); var capsResolution = END_CAPS_RESOLUTION; //matriz de rotacion del vector de dibujado var angleStep = FastMath.TWO_PI / capsResolution; var rotationMatrix = TGCMatrix.RotationAxis(-upVector, angleStep); float angle = 0; //transformacion que se le aplicara a cada vertice var transformation = Transform; var bcInverseRadius = 1 / BoundingCylinder.Radius; //arrays donde guardamos los puntos dibujados var topCapDraw = new TGCVector3[capsResolution]; var bottomCapDraw = new TGCVector3[capsResolution]; //variables temporales utilizadas para el texture mapping float u; for (var i = 0; i < capsResolution; i++) { //establecemos los vertices de las tapas topCapDraw[i] = upVector + n * TopRadius * bcInverseRadius; bottomCapDraw[i] = -upVector + n * BottomRadius * bcInverseRadius; u = angle / FastMath.TWO_PI; //triangulos de la cara lateral (strip) sideTrianglesVertices[2 * i] = new CustomVertex.PositionColoredTextured(topCapDraw[i], color, u, 0); sideTrianglesVertices[2 * i + 1] = new CustomVertex.PositionColoredTextured(bottomCapDraw[i], color, u, 1); //rotamos el vector de dibujado n.TransformNormal(rotationMatrix); angle += angleStep; } //cerramos la cara lateral sideTrianglesVertices[2 * capsResolution] = new CustomVertex.PositionColoredTextured(topCapDraw[0], color, 1, 0); sideTrianglesVertices[2 * capsResolution + 1] = new CustomVertex.PositionColoredTextured(bottomCapDraw[0], color, 1, 1); }
private double FaceVariance(short v1, short v2, short v3) { double MaxVar = 0; if ((v1 - v2 <= 1 && v1 - v2 >= -1) || (v3 - v2 <= 1 && v3 - v2 >= -1) || v3 == v1) { MaxVar = 0; // minimal face, no variance } else { try { // find vertice in middle of hypothenuse short mid_hyp_indice = MidHypVerticeIndice(v1, v3); // find real elevation in middle of hypothenuse CustomVertex.PositionColoredTextured vh = this._elevatedVertices[mid_hyp_indice]; Vector3d v = SMath.CartesianToSpherical((double)vh.X, (double)vh.Y, (double)vh.Z); double real = v.X - this._layerRadius; // find extrapolated elevation in middle hyp. double xe = (this._elevatedVertices[v1].X + this._elevatedVertices[v3].X) / 2; double ye = (this._elevatedVertices[v1].Y + this._elevatedVertices[v3].Y) / 2; double ze = (this._elevatedVertices[v1].Z + this._elevatedVertices[v3].Z) / 2; v = SMath.CartesianToSpherical(xe, ye, ze); double extrapolated = v.X - this._layerRadius; // variance Note: could be done w/out MathEngine by computing raw cartesian distance MaxVar = real - extrapolated; // recurse for potential childs until unit face if (v2 != v1 || mid_hyp_indice != v2 || v1 != v3) { MaxVar = Math.Max(MaxVar, FaceVariance(v2, mid_hyp_indice, v1)); } if (v3 != v1 || mid_hyp_indice != v2 || v2 != v3) { MaxVar = Math.Max(MaxVar, FaceVariance(v3, mid_hyp_indice, v2)); } } catch { } } return(MaxVar); }
/// <summary> /// Actualiza los vertices segun los valores de HeightmapData /// </summary> public void updateVertices() { minIntensity = -1; maxIntensity = 0; for (int i = 0; i < vertices.Length; i++) { CustomVertex.PositionColoredTextured v = vertices[i]; float intensity = heightmapData[(int)vertices[i].X, (int)vertices[i].Z]; vertices[i].Y = intensity; if (intensity > maxIntensity) { maxIntensity = intensity; } if (minIntensity == -1 || intensity < minIntensity) { minIntensity = intensity; } } vbTerrain.SetData(vertices, 0, LockFlags.None); aabb.setExtremes(new Vector3(0, minIntensity, 0), new Vector3(HeightmapData.GetLength(0), maxIntensity, HeightmapData.GetLength(1))); }
/// <summary> /// Fill the trees vertex buffer /// </summary> public void CreateTreeData(object sender, EventArgs e) { VertexBuffer vb = (VertexBuffer)sender; // Copy tree mesh data into vertexbuffer CustomVertex.PositionColoredTextured[] v = new CustomVertex.PositionColoredTextured[NumberTrees * 4]; int iTree; int offsetIndex = 0; for (iTree = 0; iTree < NumberTrees; iTree++) { v[offsetIndex + 0] = ((Tree)trees[iTree]).v0; v[offsetIndex + 1] = ((Tree)trees[iTree]).v1; v[offsetIndex + 2] = ((Tree)trees[iTree]).v2; v[offsetIndex + 3] = ((Tree)trees[iTree]).v3; Tree t = (Tree)trees[iTree]; t.offsetIndex = offsetIndex; trees[iTree] = t; offsetIndex += 4; } vb.SetData(v, 0, 0); }
public override void Generate(ref Device device) { worldMatrix = device.Transform.World; z = 0.0f; bounds = new System.Drawing.RectangleF(0.0f, 0.0f, 0.1f, 0.1f); texture = Microsoft.DirectX.Direct3D.TextureLoader.FromFile( device, Environment.CurrentDirectory + "\\Texture\\Cursor\\MOUSE_POINTER.BMP", 0, 0, 1, Usage.None, Format.Unknown, Pool.Managed, Filter.None, Filter.None, System.Drawing.Color.Black.ToArgb()); float yOffSet = bounds.Height / 2; vertices = new CustomVertex.PositionColoredTextured[4]; vertices[0].Position = new Vector3(bounds.X, bounds.Y + yOffSet, z); vertices[0].Tu = 1.0f; vertices[0].Tv = 0.0f; vertices[0].Color = System.Drawing.Color.White.ToArgb(); vertices[1].Position = new Vector3(bounds.X, bounds.Y - yOffSet, z); vertices[1].Tu = 1.0f; vertices[1].Tv = 1.0f; vertices[1].Color = System.Drawing.Color.White.ToArgb(); vertices[2].Position = new Vector3(bounds.X + bounds.Width, bounds.Y + yOffSet, z); vertices[2].Tu = 0.0f; vertices[2].Tv = 0.0f; vertices[2].Color = System.Drawing.Color.White.ToArgb(); vertices[3].Position = new Vector3(bounds.X + bounds.Width, bounds.Y - yOffSet, z); vertices[3].Tu = 0.0f; vertices[3].Tv = 1.0f; vertices[3].Color = System.Drawing.Color.White.ToArgb(); }
/// <summary> /// Renders a series of vertexs as a polygon. /// Color, scale, rotation and offset all effect the rendering of a polygon. /// </summary> /// <param name="verts">Array of vertexs to render.</param> /// <param name="Filled">If true the polygon will be filled in, else it will be hollow.</param> void IGraphicsDriver.RenderPolygon(Vertex[] polyVerts, bool filled) { // Create an array of vertexs. CustomVertex.PositionColoredTextured[] verts = new CustomVertex.PositionColoredTextured[filled ? polyVerts.Length : polyVerts.Length + 1]; float x, y; for (int i = 0; i < polyVerts.Length; i++) { x = _resolutionOffset[0] + ((polyVerts[i].X + _offset[0]) * _resolutionScale[0]); y = _resolutionOffset[1] + ((polyVerts[i].Y + _offset[1]) * _resolutionScale[1]); verts[i] = new CustomVertex.PositionColoredTextured(x, y, polyVerts[i].Z, _vertexColors[0], 0, 0); } if (filled == false) { x = _resolutionOffset[0] + ((polyVerts[0].X + _offset[0]) * _resolutionScale[0]); y = _resolutionOffset[1] + ((polyVerts[0].Y + _offset[1]) * _resolutionScale[1]); verts[polyVerts.Length] = new CustomVertex.PositionColoredTextured(x, y, polyVerts[0].Z, _vertexColors[0], 0, 0); } // Alert: SLOW SLOW SLOW!, This can be speed up if the vertexs are precompiled to a buffer. // Set transform and render UploadTextureAndBuffer(null, null); // This could probably be done more elegently, but it works. if (_currentShader != null) { int passes = _currentShader.Begin(); for (int i = 0; i < passes; i++) { _currentShader.BeginPass(i); _dx9Device.DrawUserPrimitives(filled ? PrimitiveType.TriangleFan : PrimitiveType.LineStrip, filled ? ((polyVerts.Length / 3) + 1) : polyVerts.Length, verts); _currentShader.FinishPass(); } _currentShader.Finish(); } else _dx9Device.DrawUserPrimitives(filled ? PrimitiveType.TriangleFan : PrimitiveType.LineStrip, filled ? ((polyVerts.Length / 3) + 1) : polyVerts.Length, verts); }
/// <summary> /// Renders a rectangle. /// Color, scale, rotation and offset all effect the rendering of a rectangle. /// </summary> /// <param name="x">Position on the x-axis to render rectangle.</param> /// <param name="y">Position on the y-axis to render rectangle.</param> /// <param name="z">Position on the z-axis to render rectangle.</param> /// <param name="width">Width of rectangle to render.</param> /// <param name="height">Height of rectangle to render.</param> /// <param name="Filled">If true the rectangle will be filled in, else it will be hollow.</param> void IGraphicsDriver.RenderRectangle(float x, float y, float z, float width, float height, bool filled) { // Work out where we should draw. float sx = _resolutionScale[0] + (Math.Abs(_scaleFactor[0]) - 1.0f); float sy = _resolutionScale[1] + (Math.Abs(_scaleFactor[1]) - 1.0f); float x0 = 0; float y0 = 0; float x1 = x0 + width; float y1 = y0 + height; float tx = ((x + _offset[0]) * _resolutionScale[0]) + _resolutionOffset[0]; float ty = ((y + _offset[1]) * _resolutionScale[1]) + _resolutionOffset[1]; float ix = (float)_angleCos * sx; float iy = -(float)_angleSin * sy; float jx = (float)_angleSin * sx; float jy = (float)_angleCos * sy; float z0 = z + _offset[2]; // Create an array of vertexs. CustomVertex.PositionColoredTextured[] verts = new CustomVertex.PositionColoredTextured[5] { new CustomVertex.PositionColoredTextured ( x0 * ix + y0 * iy + tx, x0 * jx + y0 * jy + ty, z0, _vertexColors[0], 0,0 ), new CustomVertex.PositionColoredTextured ( x1 * ix + y0 * iy + tx, x1 * jx + y0 * jy + ty, z0, _vertexColors[1], 0,0 ), new CustomVertex.PositionColoredTextured ( x1 * ix + y1 * iy + tx, x1 * jx + y1 * jy + ty, z0, _vertexColors[2], 0,0 ), new CustomVertex.PositionColoredTextured ( x0 * ix + y1 * iy + tx, x0 * jx + y1 * jy + ty, z0, _vertexColors[3], 0,0 ), new CustomVertex.PositionColoredTextured ( x0 * ix + y0 * iy + tx, x0 * jx + y0 * jy + ty, z0, _vertexColors[0], 0,0 ), }; // Render UploadTextureAndBuffer(null, null); if (_currentShader != null) { int passes = _currentShader.Begin(); for (int i = 0; i < passes; i++) { _currentShader.BeginPass(i); _dx9Device.DrawUserPrimitives((filled ? PrimitiveType.TriangleFan : PrimitiveType.LineStrip), (filled ? 2 : 4), verts); _currentShader.FinishPass(); } _currentShader.Finish(); } else _dx9Device.DrawUserPrimitives((filled ? PrimitiveType.TriangleFan : PrimitiveType.LineStrip), (filled ? 2 : 4), verts); }
/// <summary> /// Renders an oval. /// Color, scale, rotation and offset all effect the rendering of an oval. /// </summary> /// <param name="x">Position on the x-axis to render oval.</param> /// <param name="y">Position on the y-axis to render oval.</param> /// <param name="z">Position on the z-axis to render oval.</param> /// <param name="width">Width of oval to render.</param> /// <param name="height">Height of oval to render.</param> /// <param name="Filled">If true the oval will be filled in, else it will be hollow.</param> void IGraphicsDriver.RenderOval(float x, float y, float z, float width, float height, bool filled) { // Work out where we should draw. float sx = _resolutionScale[0] + (Math.Abs(_scaleFactor[0]) - 1.0f); float sy = _resolutionScale[1] + (Math.Abs(_scaleFactor[1]) - 1.0f); float x0 = 0; float y0 = 0; float x1 = x0 + width; float y1 = y0 + height; float tx = ((x + _offset[0]) * sx) + _resolutionOffset[0]; float ty = ((y + _offset[1]) * sy) + _resolutionOffset[1]; float ix = (float)_angleCos * sx; float iy = -(float)_angleSin * sy; float jx = (float)_angleSin * sx; float jy = (float)_angleCos * sy; float z0 = z + _offset[2]; float xr = (x1 - x0) * 0.5f; float yr = (y1 - y0) * 0.5f; int segs = (int)(Math.Abs(xr) + Math.Abs(yr)); segs = (int)Math.Max(segs, 12) &~ 3; x0 += xr; y0 += yr; CustomVertex.PositionColoredTextured[] verts = new CustomVertex.PositionColoredTextured[segs + (filled == true ? 0 : 1)]; for (int i = 0; i < segs; i++) { float th = -i * 360.0f / segs; float vx = x0 + (float)Math.Cos(MathMethods.DegreesToRadians(th)) * xr; float vy = y0 - (float)Math.Sin(MathMethods.DegreesToRadians(th)) * yr; verts[i].X = vx * ix + vy * iy + tx; verts[i].Y = vx * jx + vy * jy + ty; verts[i].Color = _vertexColors[0]; } if (filled == false) { verts[verts.Length - 1].X = verts[0].X; verts[verts.Length - 1].Y = verts[0].Y; verts[verts.Length - 1].Color = verts[0].Color;; } // Render! UploadTextureAndBuffer(null, null); if (_currentShader != null) { int passes = _currentShader.Begin(); for (int i = 0; i < passes; i++) { _currentShader.BeginPass(i); _dx9Device.DrawUserPrimitives((filled ? PrimitiveType.TriangleFan : PrimitiveType.LineStrip), filled ? segs - 2 : segs, verts); _currentShader.FinishPass(); } _currentShader.Finish(); } else _dx9Device.DrawUserPrimitives((filled ? PrimitiveType.TriangleFan : PrimitiveType.LineStrip), filled ? segs - 2 : segs, verts); }
/// <summary> /// Renders a single pixel to the screen. /// Color and offset effect the rendering of a pixel. /// </summary> /// <param name="x">Position on the x-axis to render pixel.</param> /// <param name="y">Position on the y-axis to render pixel.</param> /// <param name="z">Position on the z-axis to render pixel.</param> void IGraphicsDriver.RenderPixel(float x, float y,float z) { // Upload null buffer. UploadTextureAndBuffer(null, null); // Work out where to render. float renderX = _resolutionOffset[0] + ((x + _offset[0]) * _resolutionScale[0]); float renderY = _resolutionOffset[1] + ((y + _offset[1]) * _resolutionScale[1]); float renderZ = z + _offset[2]; // Create vertexs CustomVertex.PositionColoredTextured[] verts = new CustomVertex.PositionColoredTextured[1] { new CustomVertex.PositionColoredTextured(renderX, renderY, renderZ, _vertexColors[0], 0, 0), }; // Render. if (_currentShader != null) { int passes = _currentShader.Begin(); for (int i = 0; i < passes; i++) { _currentShader.BeginPass(i); _dx9Device.DrawUserPrimitives(PrimitiveType.PointList, 1, verts); _currentShader.FinishPass(); } _currentShader.Finish(); } else _dx9Device.DrawUserPrimitives(PrimitiveType.PointList, 1, verts); }
/// <summary> /// Creates a PositionColoredTextured 1/4 sphere centered on zero /// (1/2 north hemisphere centered on lon 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 ProjectedRings(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.PositionColoredTextured.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.PositionColoredTextured), LockFlags.None, ranks); // Set the vertex buffer int vertIndex = 0; for (int stack = 0; stack <= stacks; stack++) { double latitude = ((float)stack / stacks * (float)90.0); for (int slice = 0; slice <= slices; slice++) { CustomVertex.PositionColoredTextured pnt = new CustomVertex.PositionColoredTextured(); double longitude = 180 - ((float)slice / slices * (float)360); Vector3 v = MathEngine.SphericalToCartesian(latitude, longitude, radius); pnt.X = v.X; pnt.Y = v.Y; pnt.Z = v.Z; // Compute Tu according to sun latitude pnt.Tu = ProjectedRingsTu(v.Y, v.Z); pnt.Tv = 0.0f; // Color and alpha int alpha = shadowOpacity - 40; if (Math.Abs(longitude) > 90 && latitude < 80) alpha = 0; if (pnt.Tu < -0.1f || pnt.Tu > 1.2) alpha = 0; pnt.Color = Color.FromArgb(alpha, 0x00, 0x00, 0x00).ToArgb(); arr.SetValue(pnt, vertIndex++); } } mesh.VertexBuffer.Unlock(); ranks[0] = indexCount; arr = mesh.LockIndexBuffer(typeof(short), LockFlags.None, ranks); int i = 0; short bottomVertex = 0; short topVertex = 0; 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); return mesh; }
protected virtual void CreateMesh(GeographicBoundingBox geographicBoundingBox, int meshPointCount, ref CustomVertex.PositionColoredTextured[] vertices, ref short[] indices) { int upperBound = meshPointCount - 1; float scaleFactor = (float)1 / upperBound; double latrange = Math.Abs(geographicBoundingBox.North - geographicBoundingBox.South); double lonrange; if (geographicBoundingBox.West < geographicBoundingBox.East) { lonrange = geographicBoundingBox.East - geographicBoundingBox.West; } else { lonrange = 360.0f + geographicBoundingBox.East - geographicBoundingBox.West; } double layerRadius = m_parentProjectedLayer.World.EquatorialRadius; int opacityColor = System.Drawing.Color.FromArgb( //m_parentProjectedLayer.Opacity, 0, 0, 0).ToArgb(); vertices = new CustomVertex.PositionColoredTextured[meshPointCount * meshPointCount]; for (int i = 0; i < meshPointCount; i++) { for (int j = 0; j < meshPointCount; j++) { double height = 0; if (m_parentProjectedLayer.World.TerrainAccessor != null) { height = m_verticalExaggeration * m_parentProjectedLayer.World.TerrainAccessor.GetElevationAt( (double)geographicBoundingBox.North - scaleFactor * latrange * i, (double)geographicBoundingBox.West + scaleFactor * lonrange * j, (double)upperBound / latrange); } Vector3 pos = MathEngine.SphericalToCartesian( geographicBoundingBox.North - scaleFactor * latrange * i, geographicBoundingBox.West + scaleFactor * lonrange * j, layerRadius + height); vertices[i * meshPointCount + j].X = pos.X; vertices[i * meshPointCount + j].Y = pos.Y; vertices[i * meshPointCount + j].Z = pos.Z; vertices[i * meshPointCount + j].Tu = j * scaleFactor; vertices[i * meshPointCount + j].Tv = i * scaleFactor; vertices[i * meshPointCount + j].Color = opacityColor; } } indices = new short[2 * upperBound * upperBound * 3]; for (int i = 0; i < upperBound; i++) { for (int j = 0; j < upperBound; j++) { indices[(2 * 3 * i * upperBound) + 6 * j] = (short)(i * meshPointCount + j); indices[(2 * 3 * i * upperBound) + 6 * j + 1] = (short)((i + 1) * meshPointCount + j); indices[(2 * 3 * i * upperBound) + 6 * j + 2] = (short)(i * meshPointCount + j + 1); indices[(2 * 3 * i * upperBound) + 6 * j + 3] = (short)(i * meshPointCount + j + 1); indices[(2 * 3 * i * upperBound) + 6 * j + 4] = (short)((i + 1) * meshPointCount + j); indices[(2 * 3 * i * upperBound) + 6 * j + 5] = (short)((i + 1) * meshPointCount + j + 1); } } }
/// <summary> /// Adds a vertex to the mesh. /// </summary> public void AddVertex( int index, Vector3 position, Color color, Vector2 texCoords ) { if ( index >= numVertices ) { Log.Write( "'index' is greater than or equal to the maximum number of vertices allowed for this Mesh." + " Max allowed vertices: " + numVertices.ToString() + " Actual value: " + index.ToString() ); throw new ArgumentOutOfRangeException( "index", index, "'index' is greater than or " + "equal to the maximum number of vertices allowed for this Mesh." ); } vertices[ index ] = new CustomVertex.PositionColoredTextured( position, color.ToArgb(), texCoords.X, texCoords.Y ); isVertexBufferUpdated = false; averagedCenter = GetAveragedCenter(); radius = ComputeRadius(); }
protected virtual void CreateMesh(GeographicBoundingBox geographicBoundingBox, int meshPointCount, ref CustomVertex.PositionColoredTextured[] vertices, ref short[] indices) { int upperBound = meshPointCount - 1; float scaleFactor = (float)1/upperBound; double latrange = Math.Abs(geographicBoundingBox.North - geographicBoundingBox.South); double lonrange; if(geographicBoundingBox.West < geographicBoundingBox.East) lonrange = geographicBoundingBox.East - geographicBoundingBox.West; else lonrange = 360.0f + geographicBoundingBox.East - geographicBoundingBox.West; double layerRadius = m_parentProjectedLayer.World.EquatorialRadius; int opacityColor = System.Drawing.Color.FromArgb( //m_parentProjectedLayer.Opacity, 0,0,0).ToArgb(); vertices = new CustomVertex.PositionColoredTextured[meshPointCount * meshPointCount]; for(int i = 0; i < meshPointCount; i++) { for(int j = 0; j < meshPointCount; j++) { double height = 0; if(m_parentProjectedLayer.World.TerrainAccessor != null) height = m_verticalExaggeration * m_parentProjectedLayer.World.TerrainAccessor.GetElevationAt( (double)geographicBoundingBox.North - scaleFactor * latrange * i, (double)geographicBoundingBox.West + scaleFactor * lonrange * j, (double)upperBound / latrange); Point3d pos = MathEngine.SphericalToCartesian( geographicBoundingBox.North - scaleFactor*latrange*i, geographicBoundingBox.West + scaleFactor*lonrange*j, layerRadius + height); vertices[i * meshPointCount + j].X = (float)pos.X; vertices[i * meshPointCount + j].Y = (float)pos.Y; vertices[i * meshPointCount + j].Z = (float)pos.Z; vertices[i*meshPointCount + j].Tu = j*scaleFactor; vertices[i*meshPointCount + j].Tv = i*scaleFactor; vertices[i*meshPointCount + j].Color = opacityColor; } } indices = new short[2 * upperBound * upperBound * 3]; for(int i = 0; i < upperBound; i++) { for(int j = 0; j < upperBound; j++) { indices[(2*3*i*upperBound) + 6*j] = (short)(i*meshPointCount + j); indices[(2*3*i*upperBound) + 6*j + 1] = (short)((i+1)*meshPointCount + j); indices[(2*3*i*upperBound) + 6*j + 2] = (short)(i*meshPointCount + j+1); indices[(2*3*i*upperBound) + 6*j + 3] = (short)(i*meshPointCount + j+1); indices[(2*3*i*upperBound) + 6*j + 4] = (short)((i+1)*meshPointCount + j); indices[(2*3*i*upperBound) + 6*j + 5] = (short)((i+1)*meshPointCount + j+1); } } }
/// <summary> /// Actualiza la caja en base a los valores configurados /// </summary> public void updateValues() { int c = color.ToArgb(); float x = size.X / 2; float y = size.Y / 2; float z = size.Z / 2; float u = uvTiling.X; float v = uvTiling.Y; float offsetU = uvOffset.X; float offsetV = uvOffset.Y; // Front face vertices[0] = new CustomVertex.PositionColoredTextured(-x, y, z, c, offsetU, offsetV); vertices[1] = new CustomVertex.PositionColoredTextured(-x, -y, z, c, offsetU, offsetV + v); vertices[2] = new CustomVertex.PositionColoredTextured(x, y, z, c, offsetU + u, offsetV); vertices[3] = new CustomVertex.PositionColoredTextured(-x, -y, z, c, offsetU, offsetV + v); vertices[4] = new CustomVertex.PositionColoredTextured(x, -y, z, c, offsetU + u, offsetV + v); vertices[5] = new CustomVertex.PositionColoredTextured(x, y, z, c, offsetU + u, offsetV); // Back face (remember this is facing *away* from the camera, so vertices should be clockwise order) vertices[6] = new CustomVertex.PositionColoredTextured(-x, y, -z, c, offsetU, offsetV); vertices[7] = new CustomVertex.PositionColoredTextured(x, y, -z, c, offsetU + u, offsetV); vertices[8] = new CustomVertex.PositionColoredTextured(-x, -y, -z, c, offsetU, offsetV + v); vertices[9] = new CustomVertex.PositionColoredTextured(-x, -y, -z, c, offsetU, offsetV + v); vertices[10] = new CustomVertex.PositionColoredTextured(x, y, -z, c, offsetU + u, offsetV); vertices[11] = new CustomVertex.PositionColoredTextured(x, -y, -z, c, offsetU + u, offsetV + v); // Top face vertices[12] = new CustomVertex.PositionColoredTextured(-x, y, z, c, offsetU, offsetV); vertices[13] = new CustomVertex.PositionColoredTextured(x, y, -z, c, offsetU + u, offsetV + v); vertices[14] = new CustomVertex.PositionColoredTextured(-x, y, -z, c, offsetU, offsetV + v); vertices[15] = new CustomVertex.PositionColoredTextured(-x, y, z, c, offsetU, offsetV); vertices[16] = new CustomVertex.PositionColoredTextured(x, y, z, c, offsetU + u, offsetV); vertices[17] = new CustomVertex.PositionColoredTextured(x, y, -z, c, offsetU + u, offsetV + v); // Bottom face (remember this is facing *away* from the camera, so vertices should be clockwise order) vertices[18] = new CustomVertex.PositionColoredTextured(-x, -y, z, c, offsetU, offsetV); vertices[19] = new CustomVertex.PositionColoredTextured(-x, -y, -z, c, offsetU, offsetV + v); vertices[20] = new CustomVertex.PositionColoredTextured(x, -y, -z, c, offsetU + u, offsetV + v); vertices[21] = new CustomVertex.PositionColoredTextured(-x, -y, z, c, offsetU, offsetV); vertices[22] = new CustomVertex.PositionColoredTextured(x, -y, -z, c, offsetU + u, offsetV + v); vertices[23] = new CustomVertex.PositionColoredTextured(x, -y, z, c, offsetU + u, offsetV); // Left face vertices[24] = new CustomVertex.PositionColoredTextured(-x, y, z, c, offsetU, offsetV); vertices[25] = new CustomVertex.PositionColoredTextured(-x, -y, -z, c, offsetU + u, offsetV + v); vertices[26] = new CustomVertex.PositionColoredTextured(-x, -y, z, c, offsetU, offsetV + v); vertices[27] = new CustomVertex.PositionColoredTextured(-x, y, -z, c, offsetU + u, offsetV); vertices[28] = new CustomVertex.PositionColoredTextured(-x, -y, -z, c, offsetU + u, offsetV + v); vertices[29] = new CustomVertex.PositionColoredTextured(-x, y, z, c, offsetU, offsetV); // Right face (remember this is facing *away* from the camera, so vertices should be clockwise order) vertices[30] = new CustomVertex.PositionColoredTextured(x, y, z, c, offsetU, offsetV); vertices[31] = new CustomVertex.PositionColoredTextured(x, -y, z, c, offsetU, offsetV + v); vertices[32] = new CustomVertex.PositionColoredTextured(x, -y, -z, c, offsetU + u, offsetV + v); vertices[33] = new CustomVertex.PositionColoredTextured(x, y, -z, c, offsetU + u, offsetV); vertices[34] = new CustomVertex.PositionColoredTextured(x, y, z, c, offsetU, offsetV); vertices[35] = new CustomVertex.PositionColoredTextured(x, -y, -z, c, offsetU + u, offsetV + v); vertexBuffer.SetData(vertices, 0, LockFlags.None); }
/// <summary> /// /// </summary> /// <param name="pVertex"></param> /// <param name="drawArgs"></param> private void SetColor(ref CustomVertex.PositionColoredTextured pVertex, DrawArgs drawArgs) { vPos.X = pVertex.X; vPos.Y = pVertex.Y; vPos.Z = pVertex.Z; // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere) vCamera.X = (float)drawArgs.WorldCamera.Position.X; vCamera.Y = (float)drawArgs.WorldCamera.Position.Y; vCamera.Z = (float)drawArgs.WorldCamera.Position.Z; Vector3 vRay = vPos - vCamera; float fFar = vRay.Length(); vRay.Normalize(); // Calculate the closest intersection of the ray with the outer atmosphere (which is the near point of the ray passing through the atmosphere) float B = 2.0f * Vector3.Dot(vCamera, vRay); float Bsq = B * B; float C = Vector3.Dot(vCamera, vCamera) - m_fOuterRadius * m_fOuterRadius; float fDet = (float)Math.Max(0.0f, B * B - 4.0f * C); float fNear = 0.5f * (-B - (float)Math.Sqrt(fDet)); bool bCameraAbove = true; for (int i = 0; i < fCameraDepth.Length; i++) { fCameraDepth[i] = 0; } for (int i = 0; i < fLightDepth.Length; i++) { fLightDepth[i] = 0; } for (int i = 0; i < fSampleDepth.Length; i++) { fSampleDepth[i] = 0; } if (fNear <= 0) { // If the near point is behind the camera, it means the camera is inside the atmosphere fNear = 0; float fCameraHeight = vCamera.Length(); float fCameraAltitude = (fCameraHeight - m_fInnerRadius) * m_fScale; bCameraAbove = fCameraHeight >= vPos.Length(); float fCameraAngle = Vector3.Dot((bCameraAbove ? -vRay : vRay), vCamera) / fCameraHeight; Interpolate(ref fCameraDepth, fCameraAltitude, 0.5f - fCameraAngle * 0.5f); } else { // Otherwise, move the camera up to the near intersection point vCamera += vRay * fNear; fFar -= fNear; fNear = 0; } // If the distance between the points on the ray is negligible, don't bother to calculate anything if (fFar <= DELTA) { pVertex.Color = System.Drawing.Color.FromArgb(255, 0, 0, 0).ToArgb(); return; } // Initialize a few variables to use inside the loop for (int i = 0; i < fRayleighSum.Length; i++) { fRayleighSum[i] = 0; } for (int i = 0; i < fMieSum.Length; i++) { fMieSum[i] = 0; } float fSampleLength = fFar / m_nSamples; float fScaledLength = fSampleLength * m_fScale; Vector3 vSampleRay = vRay * fSampleLength; // Start at the center of the first sample ray, and loop through each of the others vPos = vCamera + vSampleRay * 0.5f; for (int i = 0; i < m_nSamples; i++) { float fHeight = vPos.Length(); // Start by looking up the optical depth coming from the light source to this point float fLightAngle = Vector3.Dot(m_vLightDirection, vPos) / fHeight; float fAltitude = (fHeight - m_fInnerRadius) * m_fScale; Interpolate(ref fLightDepth, fAltitude, 0.5f - fLightAngle * 0.5f); // If no light light reaches this part of the atmosphere, no light is scattered in at this point if (fLightDepth[0] < DELTA) { continue; } // Get the density at this point, along with the optical depth from the light source to this point float fRayleighDensity = fScaledLength * fLightDepth[0]; float fRayleighDepth = fLightDepth[1]; float fMieDensity = fScaledLength * fLightDepth[2]; float fMieDepth = fLightDepth[3]; // If the camera is above the point we're shading, we calculate the optical depth from the sample point to the camera // Otherwise, we calculate the optical depth from the camera to the sample point if (bCameraAbove) { float fSampleAngle = Vector3.Dot(-vRay, vPos) / fHeight; Interpolate(ref fSampleDepth, fAltitude, 0.5f - fSampleAngle * 0.5f); fRayleighDepth += fSampleDepth[1] - fCameraDepth[1]; fMieDepth += fSampleDepth[3] - fCameraDepth[3]; } else { float fSampleAngle = Vector3.Dot(vRay, vPos) / fHeight; Interpolate(ref fSampleDepth, fAltitude, 0.5f - fSampleAngle * 0.5f); fRayleighDepth += fCameraDepth[1] - fSampleDepth[1]; fMieDepth += fCameraDepth[3] - fSampleDepth[3]; } // Now multiply the optical depth by the attenuation factor for the sample ray fRayleighDepth *= m_Kr4PI; fMieDepth *= m_Km4PI; // Calculate the attenuation factor for the sample ray fAttenuation[0] = (float)Math.Exp(-fRayleighDepth / m_fWavelength4[0] - fMieDepth); fAttenuation[1] = (float)Math.Exp(-fRayleighDepth / m_fWavelength4[1] - fMieDepth); fAttenuation[2] = (float)Math.Exp(-fRayleighDepth / m_fWavelength4[2] - fMieDepth); fRayleighSum[0] += fRayleighDensity * fAttenuation[0]; fRayleighSum[1] += fRayleighDensity * fAttenuation[1]; fRayleighSum[2] += fRayleighDensity * fAttenuation[2]; fMieSum[0] += fMieDensity * fAttenuation[0]; fMieSum[1] += fMieDensity * fAttenuation[1]; fMieSum[2] += fMieDensity * fAttenuation[2]; // Move the position to the center of the next sample ray vPos += vSampleRay; } // Calculate the angle and phase values (this block of code could be handled by a small 1D lookup table, or a 1D texture lookup in a pixel shader) float fAngle = (float)Vector3.Dot(-vRay, m_vLightDirection); float[] fPhase = new float[2]; float fAngle2 = fAngle * fAngle; float g2 = m_g * m_g; fPhase[0] = 0.75f * (1.0f + fAngle2); fPhase[1] = 1.5f * ((1 - g2) / (2 + g2)) * (1.0f + fAngle2) / (float)Math.Pow(1 + g2 - 2 * m_g * fAngle, 1.5f); fPhase[0] *= m_Kr * m_ESun; fPhase[1] *= m_Km * m_ESun; // Calculate the in-scattering color and clamp it to the max color value float[] fColor = new float[3] { 0, 0, 0 }; fColor[0] = fRayleighSum[0] * fPhase[0] / m_fWavelength4[0] + fMieSum[0] * fPhase[1]; fColor[1] = fRayleighSum[1] * fPhase[0] / m_fWavelength4[1] + fMieSum[1] * fPhase[1]; fColor[2] = fRayleighSum[2] * fPhase[0] / m_fWavelength4[2] + fMieSum[2] * fPhase[1]; fColor[0] = (float)Math.Min(fColor[0], 1.0f); fColor[1] = (float)Math.Min(fColor[1], 1.0f); fColor[2] = (float)Math.Min(fColor[2], 1.0f); // Compute alpha transparency (PM 2006-11-19) float alpha = (fColor[0] + fColor[1] + fColor[2]) / 3; // Average luminosity alpha = (float)Math.Min(alpha + 0.50, 1f); // increase opacity // Last but not least, set the color pVertex.Color = System.Drawing.Color.FromArgb((byte)(alpha * 255), (byte)(fColor[0] * 255), (byte)(fColor[1] * 255), (byte)(fColor[2] * 255)).ToArgb(); }
public override void Render() { PreRender(); //Ver si cambio la textura var selectedTexture = (string)Modifiers["Texture image"]; if (currentTexurePah != selectedTexture) { currentTexurePah = selectedTexture; loadTexture(D3DDevice.Instance.Device, currentTexurePah); } //Crear triangulo segun datos del usuario var data = new CustomVertex.PositionColoredTextured[3]; //vertice 1 var v1 = (Vector3)Modifiers["vertex1"]; var t1 = (Vector2)Modifiers["texCoord1"]; data[0] = new CustomVertex.PositionColoredTextured( v1.X, v1.Y, v1.Z, ((Color)Modifiers["color1"]).ToArgb(), t1.X, t1.Y); //vertice 2 var v2 = (Vector3)Modifiers["vertex2"]; var t2 = (Vector2)Modifiers["texCoord2"]; data[1] = new CustomVertex.PositionColoredTextured( v2.X, v2.Y, v2.Z, ((Color)Modifiers["color2"]).ToArgb(), t2.X, t2.Y); //vertice 3 var v3 = (Vector3)Modifiers["vertex3"]; var t3 = (Vector2)Modifiers["texCoord3"]; data[2] = new CustomVertex.PositionColoredTextured( v3.X, v3.Y, v3.Z, ((Color)Modifiers["color3"]).ToArgb(), t3.X, t3.Y); //Rotacion var rotation = (float)Modifiers["rotation"]; D3DDevice.Instance.Device.Transform.World = Matrix.Identity * Matrix.RotationY(rotation); //Habilitar textura var textureEnable = (bool)Modifiers["TextureEnable"]; if (textureEnable) { D3DDevice.Instance.Device.SetTexture(0, texture); } else { D3DDevice.Instance.Device.SetTexture(0, null); } //Render triangulo D3DDevice.Instance.Device.VertexFormat = CustomVertex.PositionColoredTextured.Format; D3DDevice.Instance.Device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, data); PostRender(); }
public override void render(float elapsedTime) { Device d3dDevice = GuiController.Instance.D3dDevice; //Ver si cambio la textura string selectedTexture = (string)GuiController.Instance.Modifiers["Texture image"]; if (currentTexurePah != selectedTexture) { currentTexurePah = selectedTexture; loadTexture(d3dDevice, currentTexurePah); } //Crear triangulo segun datos del usuario CustomVertex.PositionColoredTextured[] data = new CustomVertex.PositionColoredTextured[3]; //vertice 1 Vector3 v1 = (Vector3)GuiController.Instance.Modifiers["vertex1"]; Vector2 t1 = (Vector2)GuiController.Instance.Modifiers["texCoord1"]; data[0] = new CustomVertex.PositionColoredTextured( v1.X, v1.Y, v1.Z, ((Color)GuiController.Instance.Modifiers["color1"]).ToArgb(), t1.X, t1.Y); //vertice 2 Vector3 v2 = (Vector3)GuiController.Instance.Modifiers["vertex2"]; Vector2 t2 = (Vector2)GuiController.Instance.Modifiers["texCoord2"]; data[1] = new CustomVertex.PositionColoredTextured( v2.X, v2.Y, v2.Z, ((Color)GuiController.Instance.Modifiers["color2"]).ToArgb(), t2.X, t2.Y); //vertice 3 Vector3 v3 = (Vector3)GuiController.Instance.Modifiers["vertex3"]; Vector2 t3 = (Vector2)GuiController.Instance.Modifiers["texCoord3"]; data[2] = new CustomVertex.PositionColoredTextured( v3.X, v3.Y, v3.Z, ((Color)GuiController.Instance.Modifiers["color3"]).ToArgb(), t3.X, t3.Y); //Rotacion float rotation = (float)GuiController.Instance.Modifiers["rotation"]; d3dDevice.Transform.World = Matrix.Identity * Matrix.RotationY(rotation); //Habilitar textura bool textureEnable = (bool)GuiController.Instance.Modifiers["TextureEnable"]; if (textureEnable) { d3dDevice.SetTexture(0, texture); } else { d3dDevice.SetTexture(0, null); } //Render triangulo d3dDevice.VertexFormat = CustomVertex.PositionColoredTextured.Format; d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleList, 1, data); }
public static void CreatePatchVertexBuffer(Device gDevice, int width, int height, Vector2 area, out VertexBuffer vBuffer) { vBuffer = new VertexBuffer(typeof(CustomVertex.PositionColoredTextured), (width * 4) + (height * 4), gDevice, Usage.WriteOnly, CustomVertex.PositionColoredTextured.Format, Pool.Managed); CustomVertex.PositionColoredTextured[] verts = (CustomVertex.PositionColoredTextured[])vBuffer.Lock(0, LockFlags.None); float xScale = area.X / (width - 1); float yScale = area.Y / (height - 1); float xTexScale = (1 - (1f / (width - 1))) / (width - 1); float yTexScale = (1 - (1f / (height - 1))) / (height - 1); int vIdx = 0; float halfPixel = (1f / (width - 1)) / 2; bool even = true; // create vertical strips (left-right) int evenClr = Color.White.ToArgb(); int oddClr = Color.Gray.ToArgb(); int zeroClr = Color.Black.ToArgb(); for (int y = 0; y < height; y++) { verts[vIdx++] = new CustomVertex.PositionColoredTextured(0, 0, y * yScale, even ? evenClr : oddClr, halfPixel, (y * yTexScale) + halfPixel /*1, 0,*/ ); verts[vIdx++] = new CustomVertex.PositionColoredTextured(xScale, 0, y * yScale, zeroClr, xTexScale + halfPixel, (y * yTexScale) + halfPixel /*1, 0,*/ ); even = !even; } even = true; for (int y = 0; y < height; y++) { verts[vIdx++] = new CustomVertex.PositionColoredTextured(area.X - xScale, 0, y * yScale, zeroClr, ((height - 1) * xTexScale) - halfPixel, (y * yTexScale) + halfPixel /*0, 0,*/ ); verts[vIdx++] = new CustomVertex.PositionColoredTextured(area.X, 0, y * yScale, even ? evenClr : oddClr, ((height - 1) * xTexScale) + halfPixel, (y * yTexScale) + halfPixel /*1, 0,*/ ); even = !even; } // create horizonal strips (bottom-top) even = true; for (int x = 0; x < width; x++) { verts[vIdx++] = new CustomVertex.PositionColoredTextured(x * xScale, 0, 0, even ? evenClr : oddClr, (x * xTexScale) + halfPixel, halfPixel /*1, 0,*/ ); verts[vIdx++] = new CustomVertex.PositionColoredTextured(x * xScale, 0, yScale, zeroClr, (x * xTexScale) + halfPixel, yTexScale + halfPixel /*1, 0,*/ ); even = !even; } even = true; for (int x = 0; x < width; x++) { verts[vIdx++] = new CustomVertex.PositionColoredTextured(x * xScale, 0, area.Y - yScale, zeroClr, (x * xTexScale) + halfPixel, ((width - 1) * yTexScale) - halfPixel /*0, 0,*/ ); verts[vIdx++] = new CustomVertex.PositionColoredTextured(x * xScale, 0, area.Y, even ? evenClr : oddClr, (x * xTexScale) + halfPixel, ((width - 1) * yTexScale) + halfPixel /*0, 0,*/ ); even = !even; } vBuffer.Unlock(); }
/// <summary> /// Crea los vertices /// </summary> private void loadVertices() { int dataIdx = 0; float width = (float)heightmapData.GetLength(0); float length = (float)heightmapData.GetLength(1); int color = Color.White.ToArgb(); vertices = new CustomVertex.PositionColoredTextured[totalVertices]; maxIntensity = 0; minIntensity = -1; for (int i = 0; i < width - 1; i++) { for (int j = 0; j < length - 1; j++) { if (heightmapData[i, j] > maxIntensity) maxIntensity = heightmapData[i, j]; if (minIntensity == -1 || heightmapData[i, j] < minIntensity) minIntensity = heightmapData[i, j]; //Vertices Vector3 v1 = new Vector3(i, heightmapData[i, j], j); Vector3 v2 = new Vector3(i, heightmapData[i, j + 1] , j + 1); Vector3 v3 = new Vector3(i + 1, heightmapData[i + 1, j], j ); Vector3 v4 = new Vector3(i + 1, heightmapData[i + 1, j + 1], j + 1); //Coordendas de textura Vector2 t1 = new Vector2(i / width, j / length); Vector2 t2 = new Vector2(i / width, (j + 1) / length); Vector2 t3 = new Vector2((i + 1) / width, j / length); Vector2 t4 = new Vector2((i + 1) / width, (j + 1) / length); //Cargar triangulo 1 vertices[dataIdx] = new CustomVertex.PositionColoredTextured(v1, color, t1.X, t1.Y); vertices[dataIdx + 1] = new CustomVertex.PositionColoredTextured(v2, color, t2.X, t2.Y); vertices[dataIdx + 2] = new CustomVertex.PositionColoredTextured(v4, color, t4.X, t4.Y); //Cargar triangulo 2 vertices[dataIdx + 3] = new CustomVertex.PositionColoredTextured(v1,color, t1.X, t1.Y); vertices[dataIdx + 4] = new CustomVertex.PositionColoredTextured(v4, color, t4.X, t4.Y); vertices[dataIdx + 5] = new CustomVertex.PositionColoredTextured(v3, color, t3.X, t3.Y); dataIdx += 6; } vbTerrain.SetData(vertices, 0, LockFlags.None); aabb.setExtremes(new Vector3(0, minIntensity, 0), new Vector3(HeightmapData.GetLength(0), maxIntensity, HeightmapData.GetLength(1))); } }
public override void Render() { PreRender(); //Triangulo 1 se corre para la izquierda. //Como tenemos un triangulo con textura y estamos haciendo una Draw primitive tenemos el problema de bingind de texturuas. //D3DDevice.Instance.Device.SetTextureStageState(0, TextureStageStates.ColorOperation, true); //D3DDevice.Instance.Device.SetTextureStageState(0, TextureStageStates.AlphaOperation, true); //FIX IT!!!!! //al realizar el clean nos aseguramos que este triangulo no tendra la textura que tiene el otro. //Especificar formato de triangulo D3DDevice.Instance.Device.VertexFormat = CustomVertex.PositionColored.Format; D3DDevice.Instance.Device.Transform.World = TGCMatrix.Translation(-2.5f, 0, 0).ToMatrix(); //Dibujar 1 primitiva (nuestro triangulo) D3DDevice.Instance.Device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, simpleTriangleData); //Triangulo 2 centro. //Ver si cambio la textura var selectedTexture = textureImageModifier.Value; if (currentTexurePah != selectedTexture) { currentTexurePah = selectedTexture; texture = TextureLoader.FromFile(D3DDevice.Instance.Device, currentTexurePah); } //Crear triangulo segun datos del usuario var data = new CustomVertex.PositionColoredTextured[3]; //vertice 1 var v1 = vertex1Modifier.Value; var t1 = texCoord1Modifier.Value; data[0] = new CustomVertex.PositionColoredTextured(v1.X, v1.Y, v1.Z, color1Modifier.Value.ToArgb(), t1.X, t1.Y); //vertice 2 var v2 = vertex2Modifier.Value; var t2 = texCoord2Modifier.Value; data[1] = new CustomVertex.PositionColoredTextured(v2.X, v2.Y, v2.Z, color2Modifier.Value.ToArgb(), t2.X, t2.Y); //vertice 3 var v3 = vertex3Modifier.Value; var t3 = texCoord3Modifier.Value; data[2] = new CustomVertex.PositionColoredTextured(v3.X, v3.Y, v3.Z, color3Modifier.Value.ToArgb(), t3.X, t3.Y); //Rotacion var rotation = rotationModifier.Value; D3DDevice.Instance.Device.Transform.World = (TGCMatrix.Identity * TGCMatrix.RotationY(rotation)).ToMatrix(); //Habilitar textura var textureEnable = textureEnableModifier.Value; if (textureEnable) { D3DDevice.Instance.Device.SetTexture(0, texture); } else { D3DDevice.Instance.Device.SetTexture(0, null); } //Render triangulo D3DDevice.Instance.Device.VertexFormat = CustomVertex.PositionColoredTextured.Format; D3DDevice.Instance.Device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, data); //Triangulo 3 se corre a la derecha. //Especificar formato de triangulos D3DDevice.Instance.Device.VertexFormat = CustomVertex.PositionColored.Format; //Cargar VertexBuffer a renderizar D3DDevice.Instance.Device.SetStreamSource(0, vertexBuffer, 0); D3DDevice.Instance.Device.Transform.World = TGCMatrix.Translation(2.5f, 0, 0).ToMatrix(); //Dibujar 1 primitiva D3DDevice.Instance.Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); PostRender(); }
void SaveTexture(string filename) { //this.frames.Sort(FrameCompare); int tWidth = 1; // frames[0].avatar.Label.Image.Width; int tHeight = 1; // frames[0].avatar.Label.Image.Height; bool flag = true; Texture outputTexture = null; CustomVertex.PositionColoredTextured[] vertexes = new CustomVertex.PositionColoredTextured[4 * frames.Count]; short[] indexes = new short[frames.Count * 6]; for (int j = 0; j < frames.Count * 4; j++) { vertexes[j].Color = Color.White.ToArgb(); vertexes[j].Position = new Vector3(0, 0, 0); } //int maxWidth, maxHeight; if (frames.Count > 1) { while (flag) { if (OTNode.wFlag) { tWidth += OTNode.widthNeed; } else { tHeight += OTNode.heightNeed; } //tWidth *= 2; // tHeight *= 2; if (outputTexture != null) { outputTexture.Dispose(); } outputTexture = new Texture(d3dDevice, tWidth, tHeight, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); Surface outputTextureSurface = outputTexture.GetSurfaceLevel(0); d3dDevice.ColorFill(outputTextureSurface, new Rectangle(0, 0, tWidth, tHeight), Color.Magenta); OTNode.target = outputTextureSurface; OTNode node = new OTNode(new Rectangle(0, 0, tWidth, tHeight)); //maxHeight = maxWidth = 0; for (int i = 0; i < frames.Count; i++) { toolStripProgressBar1.Value = (int)((float)(i + 1) / frames.Count * 100); this.Update(); Rectangle rect = node.Insert(frames[i]); if (rect == Rectangle.Empty) { flag = true; break; } else { flag = false; } //if (rect.Right > maxWidth) // maxWidth = rect.Right; //if (rect.Bottom > maxHeight) // maxHeight = rect.Bottom; vertexes[i * 4].X = -frames[i].centerPoint.X; vertexes[i * 4].Y = frames[i].centerPoint.Y - frames[i].avatar.Label.Image.Height; vertexes[i * 4 + 1].X = vertexes[i * 4].X; vertexes[i * 4 + 1].Y = frames[i].centerPoint.Y; vertexes[i * 4 + 2].X = frames[i].avatar.Label.Image.Width - frames[i].centerPoint.X;; vertexes[i * 4 + 2].Y = vertexes[i * 4 + 1].Y; vertexes[i * 4 + 3].X = vertexes[i * 4 + 2].X; vertexes[i * 4 + 3].Y = vertexes[i * 4].Y; vertexes[i * 4].Tu = (rect.Left + 1) / (float)tWidth; vertexes[i * 4].Tv = (rect.Bottom - 1) / (float)tHeight; vertexes[i * 4 + 1].Tu = vertexes[i * 4].Tu; vertexes[i * 4 + 1].Tv = (rect.Top + 1) / (float)tHeight; vertexes[i * 4 + 2].Tu = (rect.Right - 1) / (float)tWidth; vertexes[i * 4 + 2].Tv = vertexes[i * 4 + 1].Tv; vertexes[i * 4 + 3].Tu = vertexes[i * 4 + 2].Tu; vertexes[i * 4 + 3].Tv = vertexes[i * 4].Tv; indexes[i * 6 + 0] = (short)(i * 4 + 0); indexes[i * 6 + 1] = (short)(i * 4 + 1); indexes[i * 6 + 2] = (short)(i * 4 + 2); indexes[i * 6 + 3] = (short)(i * 4 + 3); indexes[i * 6 + 4] = (short)(i * 4 + 0); indexes[i * 6 + 5] = (short)(i * 4 + 2); } } } else { int i = 0; tWidth = frames[0].avatar.Label.Image.Width; tHeight = frames[0].avatar.Label.Image.Height; Rectangle rect = new Rectangle(0, 0, frames[0].avatar.Label.Image.Width, frames[0].avatar.Label.Image.Height); vertexes[i * 4].X = -frames[i].centerPoint.X; vertexes[i * 4].Y = frames[i].centerPoint.Y - frames[i].avatar.Label.Image.Height; vertexes[i * 4 + 1].X = vertexes[i * 4].X; vertexes[i * 4 + 1].Y = frames[i].centerPoint.Y; vertexes[i * 4 + 2].X = frames[i].avatar.Label.Image.Width - frames[i].centerPoint.X;; vertexes[i * 4 + 2].Y = vertexes[i * 4 + 1].Y; vertexes[i * 4 + 3].X = vertexes[i * 4 + 2].X; vertexes[i * 4 + 3].Y = vertexes[i * 4].Y; vertexes[i * 4].Tu = (rect.Left + 1) / (float)tWidth; vertexes[i * 4].Tv = (rect.Bottom - 1) / (float)tHeight; vertexes[i * 4 + 1].Tu = vertexes[i * 4].Tu; vertexes[i * 4 + 1].Tv = (rect.Top + 1) / (float)tHeight; vertexes[i * 4 + 2].Tu = (rect.Right - 1) / (float)tWidth; vertexes[i * 4 + 2].Tv = vertexes[i * 4 + 1].Tv; vertexes[i * 4 + 3].Tu = vertexes[i * 4 + 2].Tu; vertexes[i * 4 + 3].Tv = vertexes[i * 4].Tv; indexes[i * 6 + 0] = (short)(i * 4 + 0); indexes[i * 6 + 1] = (short)(i * 4 + 1); indexes[i * 6 + 2] = (short)(i * 4 + 2); indexes[i * 6 + 3] = (short)(i * 4 + 3); indexes[i * 6 + 4] = (short)(i * 4 + 0); indexes[i * 6 + 5] = (short)(i * 4 + 2); outputTexture = frames[0].texture; } Mesh mesh = new Mesh(2 * frames.Count, 4 * frames.Count, MeshFlags.Managed, CustomVertex.PositionColoredTextured.Format, d3dDevice); mesh.SetVertexBufferData(vertexes, LockFlags.None); mesh.SetIndexBufferData(indexes, LockFlags.None); //--------------------------- //Setting one of these does NOT work. You MUST set both. AttributeRange[] attributeTable = new AttributeRange[frames.Count]; int[] attributes = mesh.LockAttributeBufferArray(LockFlags.None); for (int i = 0; i < frames.Count; i++) { attributes[i * 2] = i; attributes[i * 2 + 1] = i; attributeTable[i].AttributeId = i; //ID is the value passed into the DrawSubset function of Mesh. attributeTable[i].FaceCount = 2; //Our subsets only have 1 face. attributeTable[i].FaceStart = i * 2; attributeTable[i].VertexCount = 4; //We need 3 vertices to make a face. attributeTable[i].VertexStart = i * 4; } mesh.UnlockAttributeBuffer(attributes); mesh.SetAttributeTable(attributeTable); //--------------------------- ExtendedMaterial[] em = new ExtendedMaterial[frames.Count]; em[0].TextureFilename = System.IO.Path.GetFileNameWithoutExtension(filename) + ".dds"; for (int i = 0; i < frames.Count; i++) { Material mat = new Material(); mat.Diffuse = Color.White; mat.Ambient = mat.Diffuse; mat.Specular = mat.Diffuse; mat.Emissive = Color.Black; em[i].Material3D = mat; } mesh.Save(System.IO.Path.GetFileNameWithoutExtension(filename) + ".sht", (int[])null, em, null, XFileFormat.Binary); TextureLoader.Save(System.IO.Path.GetFileNameWithoutExtension(filename) + ".dds", ImageFileFormat.Dds, outputTexture); }
/// <summary> /// Initializes all the Textures based on the configuration settings /// </summary> private void InitDeviceMem() { // generic quad vertex buffer try { int color = Color.White.ToArgb(); this.GenericQuad = new VertexBuffer(typeof(CustomVertex.PositionColoredTextured), 4, display, Usage.Dynamic, CustomVertex.TransformedColoredTextured.Format, Pool.Default); Microsoft.DirectX.GraphicsStream stm = GenericQuad.Lock(0, 0, 0); CustomVertex.PositionColoredTextured[] verts = (CustomVertex.PositionColoredTextured[])GenericQuad.Lock(0, LockFlags.None); // Bottom left verts[0] = new CustomVertex.PositionColoredTextured( new Vector3( -0.5f, 0.5f, 0), color, 0.0f, 1.0f); // Top left verts[1] = new CustomVertex.PositionColoredTextured( new Vector3( -0.5f, -0.5f, 0), color, 0.0f, 0.0f); // Bottom right verts[2] = new CustomVertex.PositionColoredTextured( new Vector3( 0.5f, 0.5f, 0), color, 1.0f, 1.0f); // Top right verts[3] = new CustomVertex.PositionColoredTextured( new Vector3( 0.5f, -0.5f, 0), color, 1.0f, 0.0f); stm.Write(verts); GenericQuad.Unlock(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message + "\n" + ex.StackTrace); try { GenericQuad.Unlock(); } catch (Exception) {} } // font objects fntOut = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font(Global.Configuration.Fonts.LabelFont, Global.Configuration.Fonts.LabelSize, Global.Configuration.Fonts.LabelStyle)); descOut = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font(Global.Configuration.Fonts.DescriptionFont, Global.Configuration.Fonts.DescriptionSize, Global.Configuration.Fonts.DescriptionStyle)); #if DEBUG dbo = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font("Tahoma", 10)); #endif // init Sprite painter SpritePainter = new Sprite(display); // get a pointer to the back buffer back = display.GetBackBuffer(0, 0, BackBufferType.Mono); // init composite texture InitCompositeTexture(); // load bg only if is not using transparency if (Global.Configuration.Appearance.Transparency != Orbit.Configuration.TransparencyMode.Real) { // load the proper background provider if (Global.Configuration.Images.UseWindowsWallpaper) { // init the wallpaper sync background provider BGProvider = new WindowsBackgroundProvider(display, SpritePainter); BGProvider.BackgroundColor = Global.Configuration.Images.BackgroundColor; } else { // init the background provider BGProvider = new BackgroundProvider(display, SpritePainter); // assing bg image if (Global.Configuration.Images.BackgroundImagePath != "") { BGProvider.BackgroundPath = Global.Configuration.Images.BackgroundImagePath; // pass on the backgorund size ImageInformation ii = Microsoft.DirectX.Direct3D.TextureLoader.ImageInformationFromFile(Global.Configuration.Images.BackgroundImagePath); BGProvider.BackgroundSize = new Size(ii.Width, ii.Height); } // pass the background color BGProvider.BackgroundColor = Color.FromArgb(0xFF, Global.Configuration.Images.BackgroundColor); } } // Load Icon Background if (Global.Configuration.Images.IconBackgroundImagePath != "") { SetIconBg(Global.Configuration.Images.IconBackgroundImagePath); } // Load Selected Icon overlay if (Global.Configuration.Images.IconSelectedImagePath != "") { SetIconSelected(Global.Configuration.Images.IconSelectedImagePath); } // load the scroll up image if (Global.Configuration.Images.ScrollUpImagePath != "") { SetScrollUp(Global.Configuration.Images.ScrollUpImagePath); } // load the scroll down image if (Global.Configuration.Images.ScrollDownImagePath != "") { SetScrollDown(Global.Configuration.Images.ScrollDownImagePath); } }
/// <summary> /// Renders a line. /// Color, scale, rotation and offset all effect the rendering of a line. /// </summary> /// <param name="x">Position on the x-axis to start rendering line.</param> /// <param name="y">Position on the y-axis to start rendering line.</param> /// <param name="z">Position on the z-axis to start rendering line.</param> /// <param name="x2">Position on the x-axis to end rendering line.</param> /// <param name="y2">Position on the y-axis to end rendering line.</param> /// <param name="z2">Position on the z-axis to end rendering line.</param> void IGraphicsDriver.RenderLine(float x, float y, float z, float x2, float y2, float z2) { if (_scaleFactor[0] < 0) { float diffX = x2 - x; x += diffX; x2 -= diffX; } if (_scaleFactor[1] < 0) { float diffY = y2 - y; y += diffY; y2 -= diffY; } // Upload empty texture and buffer. UploadTextureAndBuffer(null, null); // Work out where to render. float renderX = _resolutionOffset[0] + ((x + _offset[0]) * _resolutionScale[0]); float renderY = _resolutionOffset[1] + ((y + _offset[1]) * _resolutionScale[1]); float renderZ = z + _offset[2]; float renderX2 = _resolutionOffset[0] + ((x2 + _offset[0]) * _resolutionScale[0]); float renderY2 = _resolutionOffset[1] + ((y2 + _offset[1]) * _resolutionScale[1]); float renderZ2 = z2 + _offset[2]; // Create an array of vertexs. CustomVertex.PositionColoredTextured[] verts = new CustomVertex.PositionColoredTextured[2] { new CustomVertex.PositionColoredTextured(renderX, renderY, renderZ, _vertexColors[0], 0, 0), new CustomVertex.PositionColoredTextured(renderX2, renderY2, renderZ2, _vertexColors[1], 1, 1), }; // Render if (_currentShader != null) { int passes = _currentShader.Begin(); for (int i = 0; i < passes; i++) { _currentShader.BeginPass(i); _dx9Device.DrawUserPrimitives(PrimitiveType.LineStrip, 1, verts); _currentShader.FinishPass(); } _currentShader.Finish(); } else _dx9Device.DrawUserPrimitives(PrimitiveType.LineStrip, 1, verts); }
/// <summary> /// Convierte el box en un TgcMesh /// </summary> /// <param name="meshName">Nombre de la malla que se va a crear</param> public TgcMesh toMesh(string meshName) { Device d3dDevice = GuiController.Instance.D3dDevice; //Obtener matriz para transformar vertices if (autoTransformEnable) { this.transform = Matrix.RotationYawPitchRoll(rotation.Y, rotation.X, rotation.Z) * Matrix.Translation(translation); } //Crear mesh con DiffuseMap if (texture != null) { //Crear Mesh Mesh d3dMesh = new Mesh(vertices.Length / 3, vertices.Length, MeshFlags.Managed, TgcSceneLoader.TgcSceneLoader.DiffuseMapVertexElements, d3dDevice); //Cargar VertexBuffer using (VertexBuffer vb = d3dMesh.VertexBuffer) { GraphicsStream data = vb.Lock(0, 0, LockFlags.None); for (int j = 0; j < vertices.Length; j++) { TgcSceneLoader.TgcSceneLoader.DiffuseMapVertex v = new TgcSceneLoader.TgcSceneLoader.DiffuseMapVertex(); CustomVertex.PositionColoredTextured vBox = vertices[j]; //vertices v.Position = Vector3.TransformCoordinate(vBox.Position, this.transform); //normals v.Normal = Vector3.Empty; //texture coordinates diffuseMap v.Tu = vBox.Tu; v.Tv = vBox.Tv; //color v.Color = vBox.Color; data.Write(v); } vb.Unlock(); } //Cargar IndexBuffer en forma plana using (IndexBuffer ib = d3dMesh.IndexBuffer) { short[] indices = new short[vertices.Length]; for (int j = 0; j < indices.Length; j++) { indices[j] = (short)j; } ib.SetData(indices, 0, LockFlags.None); } //Calcular normales d3dMesh.ComputeNormals(); //Malla de TGC TgcMesh tgcMesh = new TgcMesh(d3dMesh, meshName, TgcMesh.MeshRenderType.DIFFUSE_MAP); tgcMesh.DiffuseMaps = new TgcTexture[] { texture.clone() }; tgcMesh.Materials = new Material[] { TgcD3dDevice.DEFAULT_MATERIAL }; tgcMesh.createBoundingBox(); tgcMesh.Enabled = true; tgcMesh.AlphaBlendEnable = this.alphaBlendEnable; return(tgcMesh); } //Crear mesh con solo color else { //Crear Mesh Mesh d3dMesh = new Mesh(vertices.Length / 3, vertices.Length, MeshFlags.Managed, TgcSceneLoader.TgcSceneLoader.VertexColorVertexElements, d3dDevice); //Cargar VertexBuffer using (VertexBuffer vb = d3dMesh.VertexBuffer) { GraphicsStream data = vb.Lock(0, 0, LockFlags.None); for (int j = 0; j < vertices.Length; j++) { TgcSceneLoader.TgcSceneLoader.VertexColorVertex v = new TgcSceneLoader.TgcSceneLoader.VertexColorVertex(); CustomVertex.PositionColoredTextured vBox = vertices[j]; //vertices v.Position = Vector3.TransformCoordinate(vBox.Position, this.transform); //normals v.Normal = Vector3.Empty; //color v.Color = vBox.Color; data.Write(v); } vb.Unlock(); } //Cargar IndexBuffer en forma plana using (IndexBuffer ib = d3dMesh.IndexBuffer) { short[] indices = new short[vertices.Length]; for (int j = 0; j < indices.Length; j++) { indices[j] = (short)j; } ib.SetData(indices, 0, LockFlags.None); } //Malla de TGC TgcMesh tgcMesh = new TgcMesh(d3dMesh, meshName, TgcMesh.MeshRenderType.VERTEX_COLOR); tgcMesh.Materials = new Material[] { TgcD3dDevice.DEFAULT_MATERIAL }; tgcMesh.createBoundingBox(); tgcMesh.Enabled = true; return(tgcMesh); } }
void DrawTextureDirect3D(Texture t, Rectangle dz, Vector3 loc, Size size, float rotation, Color color) { if (Devices.D3DDev.Disposed) { return; } if (t == null) { return; } Devices.D3DDev.SetTexture(0, t); int w, h; w = Devices.D3DDev.PresentationParameters.BackBufferWidth; h = Devices.D3DDev.PresentationParameters.BackBufferHeight; loc.X -= w / 2; loc.Y -= h / 2; loc.Y = -loc.Y; Size s = new Size(t.GetSurfaceLevel(0).Description.Width,t.GetSurfaceLevel(0).Description.Height); float fx, fy, tx, ty; //if (Util.Is2PowSize(t.SizePixel)) //{ // fx = (float)dz.Left / (float)s.Width; // tx = (float)dz.Right / (float)s.Width; // fy = (float)dz.Top / (float)s.Height; // ty = (float)dz.Bottom / (float)s.Height; //} //else { fx = ((float)dz.Left + (float)Options.UVOffsetX) / (float)s.Width; tx = ((float)dz.Right + (float)Options.UVOffsetX) / (float)s.Width; fy = ((float)dz.Top + (float)Options.UVOffsetY) / (float)s.Height; ty = ((float)dz.Bottom + (float)Options.UVOffsetY) / (float)s.Height; } //Vector3 cp = new Vector3(0, 0, 0); Vector3 cp = loc; vertexs[0] = new CustomVertex.PositionColoredTextured(cp, color.ToArgb(), fx, fy); vertexs[1] = new CustomVertex.PositionColoredTextured(cp.X + size.Width, cp.Y - size.Height, cp.Z, color.ToArgb(), tx, ty); vertexs[2] = new CustomVertex.PositionColoredTextured(cp.X, cp.Y - size.Height, cp.Z, color.ToArgb(), fx, ty); vertexs[3] = new CustomVertex.PositionColoredTextured(cp, color.ToArgb(), fx, fy); vertexs[4] = new CustomVertex.PositionColoredTextured(cp.X + size.Width, cp.Y, cp.Z, color.ToArgb(), tx, fy); vertexs[5] = new CustomVertex.PositionColoredTextured(cp.X + size.Width, cp.Y - size.Height, cp.Z, color.ToArgb(), tx, ty); //loc = Util.Vector3MulInt(loc, 2); //Devices.D3DDev.Transform.World = Matrix.RotationX(0.5f); //Devices.D3DDev.Transform.World = Matrix.RotationX(-2); Devices.D3DDev.DrawUserPrimitives(PrimitiveType.TriangleList, 2, vertexs); //Devices.VertexBuffer.SetData(vertexs, 0, LockFlags.None); //Devices.D3DDev.DrawPrimitives(PrimitiveType.TriangleList, 0, 2); }