public void LoadContent(ContentManager content, GraphicsDeviceManager graphicsDeviceManager) { texture = content.Load<Texture2D>("brick_texture_map"); wall = new VertexPositionTexture[22]; wall[0] = new VertexPositionTexture(new Vector3(200, 0, 200), new Vector2(0, 0)); wall[1] = new VertexPositionTexture(new Vector3(200, 200, 200), new Vector2(2, 0)); wall[2] = new VertexPositionTexture(new Vector3(0, 0, 200), new Vector2(0, 2)); wall[3] = new VertexPositionTexture(new Vector3(0, 200, 200), new Vector2(2, 2)); wall[4] = new VertexPositionTexture(new Vector3(0, 0, 220), new Vector2(0, 0)); wall[5] = new VertexPositionTexture(new Vector3(0, 200, 220), new Vector2(2, 0)); wall[6] = new VertexPositionTexture(new Vector3(200, 0, 220), new Vector2(0, 2)); wall[7] = new VertexPositionTexture(new Vector3(200, 200, 220), new Vector2(2, 2)); wall[8] = new VertexPositionTexture(new Vector3(200, 0, 200), new Vector2(0, 0)); wall[9] = new VertexPositionTexture(new Vector3(200, 200, 220), new Vector2(2, 0)); wall[10] = new VertexPositionTexture(new Vector3(200, 200, 200), new Vector2(2, 2)); wall[11] = new VertexPositionTexture(new Vector3(0, 200, 220), new Vector2(0, 2)); wall[12] = new VertexPositionTexture(new Vector3(0, 200, 200), new Vector2(0, 0)); // Set vertex data in VertexBuffer vertexBuffer = new VertexBuffer(graphicsDeviceManager.GraphicsDevice, typeof(VertexPositionTexture), wall.Length, BufferUsage.None); vertexBuffer.SetData(wall); // Initialize the BasicEffect effect = new BasicEffect(graphicsDeviceManager.GraphicsDevice); }
public void Draw(DrawMode Mode,VertexBuffer VB) { if(VB == null) throw new Exception("Must have Vertex Buffer"); if(VB.Normal != null) { gl.EnableClientState(NORMAL_ARRAY); gl.BindBuffer((uint)VB.Normal.BType,VB.Normal.B); gl.NormalPointer((uint)VB.Normal.T,0,null); } else gl.DisableClientState(NORMAL_ARRAY); if(VB.TexCoord != null) { gl.EnableClientState(TEXTURE_COORD_ARRAY); gl.BindBuffer((uint)VB.TexCoord.BType,VB.TexCoord.B); gl.TexCoordPointer(VB.TexCoord.Size,(uint)VB.TexCoord.T,0,null); } else gl.DisableClientState(TEXTURE_COORD_ARRAY); gl.EnableClientState(VERTEX_ARRAY); gl.BindBuffer((uint)VB.BType,VB.B); gl.VertexPointer(VB.Size,(uint)VB.T,0,null); gl.DrawArrays((uint)Mode,0,VB.Count); gl.DisableClientState(VERTEX_ARRAY); gl.DisableClientState(NORMAL_ARRAY); gl.DisableClientState(TEXTURE_COORD_ARRAY); }
protected override void LoadBatchInfo(GraphicFactory factory, out BatchInformation[][] BatchInformations) { TreeProfile t = factory.GetAsset<TreeProfile>(profileName); if (!String.IsNullOrEmpty(LeaftextureName)) { t.LeafTexture = factory.GetAsset<Texture2D>(LeaftextureName); } if (!String.IsNullOrEmpty(trunktextureName)) { t.TrunkTexture = factory.GetAsset<Texture2D>(trunktextureName); } tree = t.GenerateSimpleTree(StaticRandom.RandomInstance); BatchInformations = new BatchInformation[2][]; vertexBufferS = new VertexBuffer[2]; indexBufferS = new IndexBuffer[2]; indexBufferS[0] = tree.TrunkMesh.IndexBuffer; vertexBufferS[0] = tree.TrunkMesh.VertexBuffer; BatchInformation bi0 = new BatchInformation(0, tree.TrunkMesh.NumberOfVertices, tree.TrunkMesh.NumberOfTriangles, 0, 0, tree.TrunkMesh.Vdeclaration, TreeVertex.SizeInBytes); BatchInformations[0] = new BatchInformation[1]; BatchInformations[0][0] = bi0; indexBufferS[1] = tree.LeafCloud.Ibuffer; vertexBufferS[1] = tree.LeafCloud.Vbuffer; BatchInformation bi1 = new BatchInformation(0, tree.LeafCloud.Numleaves * 4, tree.LeafCloud.Numleaves * 2, 0, 0, tree.LeafCloud.Vdeclaration, LeafVertex.SizeInBytes); BatchInformations[1] = new BatchInformation[1]; BatchInformations[1][0] = bi1; }
public static void RenderVertexPositionColorList(GraphicsDevice gd, BasicEffect effect, Matrix world, Matrix view, Matrix proj, VertexPositionColor[] vertices, VertexDeclaration vertexDeclaration, VertexBuffer vertex_buffer) { // gd.VertexDeclaration = vertexDeclaration; effect.World = world; effect.View = view; effect.Projection = proj; effect.VertexColorEnabled = true; if (vertex_buffer == null) { vertex_buffer = new VertexBuffer(gd, typeof(VertexPositionColor), vertices.Length, BufferUsage.WriteOnly); vertex_buffer.SetData<VertexPositionColor>(vertices); } foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); gd.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, vertices, 0, vertices.Length / 3); } }
public ChunkRenderer(Chunk chunk, World world) { this.WorldObj = world; this.Chunk = chunk; this.Buffer = new VertexBuffer(); }
public void VertexBuffer_ConstructorTest() { var vb = new VertexBuffer<TransformedColoredVertex>(Device); Assert.IsNull(vb.RawBuffer); Assert.AreEqual(20, vb.ElementSize); Assert.AreEqual(0, vb.Count); }
public static void InitializeGraphics(GraphicsDevice graphicsDevice, Triangle[] triangles, Guid id) { var basicEffect = new BasicEffect(graphicsDevice) { LightingEnabled = false, VertexColorEnabled = false }; var index = 0; var vertices = new VertexPositionColor[triangles.SelectMany(i => i.Points).Count()]; foreach (var point in triangles.SelectMany(triangle => triangle.Points)) vertices[index++] = new VertexPositionColor(new Vector3(point.X, point.Y, point.Z), Color.White); var vertexBuffer = new VertexBuffer(graphicsDevice, typeof (VertexPositionColor), vertices.Length, BufferUsage.None); vertexBuffer.SetData(vertices); Subscriptions.Add(id, new RendererHelperData { BasicEffect = basicEffect, VertexBuffer = vertexBuffer }); }
public static Model FromScene(Scene scene, Device device) { VertexDeclaration vertexDeclaration = new VertexDeclaration(device, VertexPositionNormalTexture.VertexElements); Model result = new Model(scene, device, vertexDeclaration); foreach (Mesh mesh in scene.Meshes) { VertexBuffer vertexBuffer = new VertexBuffer(device, mesh.Positions.Count * VertexPositionNormalTexture.SizeInBytes, Usage.WriteOnly, VertexFormat.None, Pool.Default); DataStream vertexDataStream = vertexBuffer.Lock(0, mesh.Positions.Count * VertexPositionNormalTexture.SizeInBytes, LockFlags.None); VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[mesh.Positions.Count]; for (int i = 0; i < vertices.Length; ++i) vertices[i] = new VertexPositionNormalTexture(mesh.Positions[i], (mesh.Normals.Count > i) ? mesh.Normals[i] : Vector3D.Zero, Point2D.Zero); vertexDataStream.WriteRange(vertices); vertexBuffer.Unlock(); IndexBuffer indexBuffer = new IndexBuffer(device, mesh.Indices.Count * sizeof(int), Usage.WriteOnly, Pool.Default, false); DataStream indexDataStream = indexBuffer.Lock(0, mesh.Indices.Count * sizeof(int), LockFlags.None); indexDataStream.WriteRange(mesh.Indices.ToArray()); indexBuffer.Unlock(); ModelMesh modelMesh = new ModelMesh(mesh, device, vertexBuffer, mesh.Positions.Count, indexBuffer, mesh.PrimitiveCount, Matrix3D.Identity, mesh.Material); result.Meshes.Add(modelMesh); } return result; }
protected override void DoInitialize() { base.DoInitialize(); { // velocity var buffer = VertexBuffer.Create(typeof(vec4), ParticleModel.particleCount, VBOConfig.Vec4, "empty", BufferUsage.DynamicCopy); unsafe { var random = new Random(); var array = (vec4*)buffer.MapBuffer(MapBufferAccess.WriteOnly); for (int i = 0; i < ParticleModel.particleCount; i++) { array[i] = new vec4( (float)(random.NextDouble() - 0.5) * 0.2f, (float)(random.NextDouble() - 0.5) * 0.2f, (float)(random.NextDouble() - 0.5) * 0.2f, 0); } buffer.UnmapBuffer(); } this.VelocityBuffer = buffer; } this.PositionBuffer = this.DataSource.GetVertexAttributeBuffer(ParticleModel.strPosition, null); }
private void CreateVertexBuffer() { vertexDeclaration = new VertexDeclaration(new VertexElement[1] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0) } ); vertexBuffer = new VertexBuffer( GraphicsDevice, vertexDeclaration, number_of_vertices, BufferUsage.None ); Vector3[] vertices = new Vector3[number_of_vertices]; vertices[0] = new Vector3(-1, 0, 0); // cw vertices[1] = new Vector3(0, 1, 0); vertices[2] = new Vector3(0, 0, 0); vertices[3] = new Vector3(0, 0, 0); // ccw vertices[4] = new Vector3(1, 0, 0); vertices[5] = new Vector3(0, 1, 0); vertexBuffer.SetData(vertices); }
public VertexBuffer GetVertexAttributeBuffer(string bufferName, string varNameInShader) { if (bufferName == strPosition) { if (positionBuffer == null) { //int length = positions.Length; //VertexBuffer buffer = VertexBuffer.Create(typeof(float), length, VBOConfig.Vec3, BufferUsage.DynamicDraw, varNameInShader); //unsafe //{ // IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly); // var array = (float*)pointer; // for (int i = 0; i < positions.Length; i++) // { // array[i] = positions[i]; // } // buffer.UnmapBuffer(); //} //this.positionBuffer = buffer; this.positionBuffer = positions.GenVertexBuffer(VBOConfig.Vec3, varNameInShader, BufferUsage.DynamicDraw); } return positionBuffer; } else { return null; } }
public static void DrawLineList(Vector3[] lineList, int vertices, Color color) { // Initialize an array of indices of type short. lineListIndices = new short[vertices]; pointList = new VertexPositionColor[vertices]; for (int p = 0; p < vertices; p++) { pointList[p] = new VertexPositionColor( lineList[p], color ); lineListIndices[p] = (short)(p); } // Initialize the vertex buffer, allocating memory for each vertex. vertexBuffer = new VertexBuffer(Game.Game.Graphics.GraphicsDevice, vertexDeclaration, vertices, BufferUsage.None); // Set the vertex buffer data to the array of vertices. vertexBuffer.SetData<VertexPositionColor>(pointList); foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) { pass.Apply(); Game.Game.Graphics.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>( PrimitiveType.LineList, pointList, 0, // vertex buffer offset to add to each element of the index buffer vertices, // number of vertices in pointList lineListIndices, // the index buffer 0, // first index element to read vertices / 2 // number of primitives to draw ); } }
public bool CreateTextures() { CustomVertex[] verts; try { string textureFile; // Load the textures, named from "walk1.bmp" to "walk10.bmp" for(int i=1; i<=10; i++) { textureFile = Application.StartupPath + @"\..\..\Images\walk" + i.ToString() + ".bmp"; textures[i-1] = TextureLoader.FromFile(device, textureFile); } // Define the vertex buffer to hold our custom vertices vertBuffer = new VertexBuffer(typeof(CustomVertex), numVerts, device, Usage.WriteOnly, customVertexFlags, Pool.Default); // Locks the memory, which will return the array to be filled verts = vertBuffer.Lock(0, 0) as CustomVertex[]; // Defines the vertices SquareVertices(verts); // Unlock the buffer, which will save our vertex information to the device vertBuffer.Unlock(); return true; } catch { return false; } }
public bool CreateTextures() { CustomVertex[] verts; //We will use blue as the transparent color Color colorKeyVal = Color.FromArgb(255, 0, 0, 255); try { //Load the walking guy textures string textureFile; for(int i=1; i<=10; i++) { textureFile = Application.StartupPath + @"\..\..\Images\walk" + i.ToString() + ".bmp"; textures[i-1] = TextureLoader.FromFile(device, textureFile); } //Load the transparent texture TranspTexture = TextureLoader.FromFile(device, Application.StartupPath + @"\..\..\Images\TranspSample.bmp", 64, 64, D3DX.Default, 0, Format.Unknown, Pool.Managed, Filter.Point, Filter.Point, colorKeyVal.ToArgb()); vertBuffer = new VertexBuffer(typeof(CustomVertex), numVerts, device, Usage.WriteOnly, customVertexFlags, Pool.Default); verts = vertBuffer.Lock(0, 0) as CustomVertex[]; SquareVertices(verts); vertBuffer.Unlock(); return true; } catch { return false; } }
public Sprite2DBatch( GraphicsContext graphics, int maxSpriteCount ) { int maxVertexCount = maxSpriteCount * 4 ; int maxIndexCount = maxSpriteCount * 6 ; graphicsContext = graphics ; #if !RESIZE_VERTEX_BUFFER vertexBuffer = new VertexBuffer( maxVertexCount, maxIndexCount, vertexFormats ) ; spriteCapacity = maxSpriteCount ; #endif // RESIZE_VERTEX_BUFFER vertexData = new Vertex[ maxVertexCount ] ; indexData = new ushort[ maxIndexCount ] ; spriteList = new Sprite2D[ maxSpriteCount ] ; sortedList = new Sprite2D[ maxSpriteCount ] ; #if ENABLE_SIN_TABLE if ( sinTable == null ) { sinTable = new float[ 4096 ] ; for ( int i = 0 ; i < 4096 ; i ++ ) { sinTable[ i ] = FMath.Sin( i * ( FMath.PI / 2048.0f ) ) ; } } #endif // ENABLE_SIN_TABLE }
public Level10(int boxesMax, int boxNeed, Vector3 spawnPoint, List<Vector3> billboardList, Theme levelTheme, BaseModel levelModel, BaseModel levelModelTwo, BaseModel[] glassModels, Goal catcher, Dictionary<OperationalMachine, bool> machines, List<Tube> tubes, LevelCompletionData data, string name) : base(10, boxesMax, boxNeed, spawnPoint, billboardList, levelTheme, levelModel, glassModels, catcher, null, machines, tubes, data, name) { currentCameraPoint = RenderingDevice.Camera.Position; boxesMaxOne = boxesMax; boxesNeedOne = boxNeed; boxesMaxTwo = 20; boxesNeedTwo = 10; spawnTheFirst = spawnPoint; spawnTheSecond = new Vector3(197.153f, -4.134f, 1.5f); catcherTheFirst = normalCatcher; catcherTheSecond = new Goal(new Vector3(313.454f, -3.801f, 5.5f), true); baseTheSecond = levelModelTwo; Vector3 pos = new Vector3(198.273f, -4.468f, 6.037f); ADVertexFormat[] verts = new ADVertexFormat[4]; verts[0] = new ADVertexFormat(new Vector3(0, 13.686f / 2, -11.359f / 2) + pos, new Vector2(0, 0), Vector3.UnitX); verts[1] = new ADVertexFormat(new Vector3(0, -13.686f / 2, -11.359f / 2) + pos, new Vector2(0, 1), Vector3.UnitX); verts[2] = new ADVertexFormat(new Vector3(0, 13.686f / 2, 11.359f / 2) + pos, new Vector2(1, 1), Vector3.UnitX); verts[3] = new ADVertexFormat(new Vector3(0, -13.686f / 2, 11.359f / 2) + pos, new Vector2(1, 0), Vector3.UnitX); buff = new VertexBuffer(RenderingDevice.GraphicsDevice, ADVertexFormat.VertexDeclaration, 4, BufferUsage.WriteOnly); buff.SetData(verts); blackTex = new Texture2D(RenderingDevice.GraphicsDevice, 1, 1); blackTex.SetData(new Color[] { new Color(0, 0, 0, 255) }); }
public Tile(Texture2D texture2D, GraphicsDeviceManager graphicsDeviceManager, Vector3 position, Vector3 dimension) { texture = texture2D; tile = new VertexPositionTexture[14]; tile[0] = new VertexPositionTexture(new Vector3(position.X, position.Y, position.Z), new Vector2(0, 0)); tile[1] = new VertexPositionTexture(new Vector3(position.X + dimension.X, position.Y, position.Z), new Vector2(1, 0)); tile[2] = new VertexPositionTexture(new Vector3(position.X, position.Y + dimension.Y, position.Z), new Vector2(0, 1)); tile[3] = new VertexPositionTexture(new Vector3(position.X + dimension.X, position.Y + dimension.Y, position.Z), new Vector2(1, 1)); tile[4] = new VertexPositionTexture(new Vector3(position.X + dimension.X, position.Y + dimension.Y, position.Z + dimension.Z), new Vector2(1, 0)); tile[5] = new VertexPositionTexture(new Vector3(position.X + dimension.X, position.Y, position.Z), new Vector2(0, 1)); tile[6] = new VertexPositionTexture(new Vector3(position.X + dimension.X, position.Y, position.Z + dimension.Z), new Vector2(0, 0)); tile[7] = new VertexPositionTexture(new Vector3(position.X, position.Y, position.Z), new Vector2(1, 1)); tile[8] = new VertexPositionTexture(new Vector3(position.X, position.Y, position.Z + dimension.Z), new Vector2(1, 0)); tile[9] = new VertexPositionTexture(new Vector3(position.X, position.Y + dimension.Y, position.Z), new Vector2(0, 1)); tile[10] = new VertexPositionTexture(new Vector3(position.X, position.Y + dimension.Y, position.Z + dimension.Z), new Vector2(0, 0)); tile[11] = new VertexPositionTexture(new Vector3(position.X + dimension.X, position.Y + dimension.Y, position.Z + dimension.Z), new Vector2(1, 0)); tile[12] = new VertexPositionTexture(new Vector3(position.X, position.Y, position.Z + dimension.Z), new Vector2(0, 1)); tile[13] = new VertexPositionTexture(new Vector3(position.X + dimension.X, position.Y, position.Z + dimension.Z), new Vector2(1, 1)); // Set vertex data in VertexBuffer vertexBuffer = new VertexBuffer(graphicsDeviceManager.GraphicsDevice, typeof(VertexPositionTexture), tile.Length, BufferUsage.None); vertexBuffer.SetData(tile); // Initialize the BasicEffect effect = new BasicEffect(graphicsDeviceManager.GraphicsDevice); }
public void Resolve(bool injectHardEdges) { _vertices = new List<VertexPositionNormalTexture>(); //ushort indIdx = 0; List<UInt16> indices = new List<UInt16>(_vertexPositions.Count); foreach (CModel model in _models) { model.HardEdgesInserted = injectHardEdges; model.IndexBufferStart = indices.Count; model.Polygons.Sort(delegate(Polygon p1, Polygon p2) { return p1.MaterialIndex.CompareTo(p2.MaterialIndex); }); model.Resolve(indices, _vertices, _vertexTextureMap, _vertexPositions); } if (_vertices.Count > 0) { _vertexBuffer = new VertexBuffer(Engine.Device, VertexPositionNormalTexture.SizeInBytes * _vertices.Count, BufferUsage.WriteOnly); _vertexBuffer.SetData<VertexPositionNormalTexture>(_vertices.ToArray()); if (!injectHardEdges) { _indexBuffer = new IndexBuffer(Engine.Device, typeof(UInt16), indices.Count, BufferUsage.WriteOnly); _indexBuffer.SetData<UInt16>(indices.ToArray()); _indices = indices; } } _vertexDeclaration = new VertexDeclaration(Engine.Device, VertexPositionNormalTexture.VertexElements); _vertexTextureMap = null; //dont need this data anymore }
protected override void onDeviceCreate(object sender, EventArgs e) { base.onDeviceCreate(sender, e); vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 100, _device, Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vertexBuffer.Created += new System.EventHandler(this.onVertexBufferCreate); this.onVertexBufferCreate(vertexBuffer, null); }
public void SetUp() { adapter = new Mock<IBufferAdapter>(); adapter.Setup(a => a.GenBuffer()) .Returns(1); buffer = new VertexBuffer<Vertex>(adapter.Object); }
public void AddVertexBuffer(VertexBufferLayoutKind[] vblk, VertexBuffer vb) { if (!m_PrepareMode) { GL.BindVertexArray(ID); } if (vb.Created) { GL.BindBuffer(BufferTarget.ArrayBuffer, vb.ID); for (int i = 0; i < vblk.Length; i++) { GL.EnableVertexAttribArray(vblk[i].AttributeID); GL.VertexAttribPointer(vblk[i].AttributeID, vblk[i].AttributeSize, (VertexAttribPointerType)vblk[i].AttributeType, vblk[i].Normalized, vblk[i].Stride, (IntPtr)vblk[i].Offset); } VertexBufferLayoutKind[] layout = new VertexBufferLayoutKind[vblk.Length]; Array.Copy(vblk, layout, layout.Length); _LayoutElements.Add(layout); _InternalBuffers.Add(vb); vb.SetUseCount(vb.InternalUseCount + 1); } if(!m_PrepareMode) { GL.BindVertexArray(0); } }
public BufferGlyph(VertexBuffer buffer, int offset, int triangles, Vector2 escape) : base(escape) { Buffer = buffer; VertexOffset = offset; TriangleCount = triangles; }
public PointsGisLayerCPU(Game game, int maxPointsCount, bool isDynamic = true) : base(game) { PointsCountToDraw = maxPointsCount; indeces = new int[maxPointsCount*6]; PointsDrawOffset = 0; SizeMultiplier = 1; var vbOptions = isDynamic ? VertexBufferOptions.Dynamic : VertexBufferOptions.Default; currentBuffer = new VertexBuffer(Game.GraphicsDevice, typeof(Gis.CartPoint), maxPointsCount * 4, vbOptions); PointsCpu = new Gis.CartPoint[maxPointsCount*4]; indBuf = new IndexBuffer(Game.GraphicsDevice, indeces.Length); for (int i = 0; i < maxPointsCount; i += 1) { indeces[i*6 + 0] = i*4 + 0; indeces[i*6 + 1] = i*4 + 1; indeces[i*6 + 2] = i*4 + 2; indeces[i*6 + 3] = i*4 + 1; indeces[i*6 + 4] = i*4 + 3; indeces[i*6 + 5] = i*4 + 2; } indBuf.SetData(indeces); shader = Game.Content.Load<Ubershader>("globe.Debug.hlsl"); factory = shader.CreateFactory(typeof(PointFlags), Primitive.TriangleList, VertexInputElement.FromStructure<Gis.CartPoint>(), BlendState.AlphaBlend, RasterizerState.CullCW, DepthStencilState.None); }
public void CreateShape() { double angle = MathHelper.TwoPi / CIRCLE_NUM_POINTS; _vertices = new VertexPositionNormalTexture[CIRCLE_NUM_POINTS + 1]; _vertices[0] = new VertexPositionNormalTexture( Vector3.Zero, Vector3.Forward, Vector2.One); for (int i = 1; i <= CIRCLE_NUM_POINTS; i++) { float x = (float)Math.Round(Math.Sin(angle * i), 4); float y = (float)Math.Round(Math.Cos(angle * i), 4); Vector3 point = new Vector3( x, y, 0.0f); _vertices[i] = new VertexPositionNormalTexture( point, Vector3.Forward, new Vector2()); } buffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionNormalTexture), _vertices.Length, BufferUsage.None); // Set the vertex buffer data to the array of vertices buffer.SetData<VertexPositionNormalTexture>(_vertices); InitializeLineStrip(); }
public override void RenderToDevice(GraphicsDevice device, BasicEffect basicEffet) { if (Visible) { if (!basicEffet.LightingEnabled) { if (isConstructed == false) Construct(); using ( VertexBuffer buffer = new VertexBuffer( device, VertexPositionColor.VertexDeclaration, points, BufferUsage.WriteOnly) ) { // Load the buffer buffer.SetData(pointList); // Send the vertex buffer to the device device.SetVertexBuffer(buffer); device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.LineList, pointList, 0, 6, lineListIndices, 0, 3); } } } }
public Sphere(float Radius, GraphicsDevice graphics, Texture2D tex, Texture2D prograde, Texture2D retrograde, Texture2D maneuverPrograde, Texture2D targetPrograde, Texture2D targetRetrograde) { this.prograde = new Bilboard (prograde, Matrix.CreateScale (1.0f)); this.retrograde = new Bilboard (retrograde, Matrix.CreateScale (1.0f)); this.maneuverPrograde = new Bilboard (maneuverPrograde, Matrix.CreateScale (1.0f)); this.targetPrograde = new Bilboard (targetPrograde, Matrix.CreateScale (1.0f)); this.targetRetrograde = new Bilboard (targetRetrograde, Matrix.CreateScale (1.0f)); texture = tex; radius = Radius; graphicd = graphics; effect = new BasicEffect(graphicd); nvertices = res * res; // 90 vertices in a circle, 90 circles in a sphere nindices = res * res * 6; vbuffer = new VertexBuffer(graphics, typeof(VertexPositionNormalTexture), nvertices, BufferUsage.WriteOnly); ibuffer = new IndexBuffer(graphics, IndexElementSize.SixteenBits, nindices, BufferUsage.WriteOnly); createspherevertices(); createindices(); vbuffer.SetData<VertexPositionNormalTexture>(vertices); ibuffer.SetData<short>(indices); effect.TextureEnabled = true; effect.LightingEnabled = true; rotQuat = Quaternion.Identity; }
void CreateVertexBuffer() { VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[number_of_vertices]; float halfWidth = (number_of_cols - 1) * 0.5f; float halfDepth = (number_of_rows - 1) * 0.5f; float du = 1.0f / (number_of_cols - 1); float dv = 1.0f / (number_of_rows - 1); for (int i = 0; i < number_of_rows; ++i) { float z = halfDepth - i; for (int j = 0; j < number_of_cols;++j) { float x = -halfWidth + j; float y = getHeight(x, z); vertices[i * number_of_cols + j].Position = new Vector3(x, y, z); vertices[i * number_of_cols + j].TextureCoordinate = new Vector2(j * du, i * dv); Vector3 normal = new Vector3(); normal.X = -0.03f * z * (float)Math.Cos(0.1f * x) - 0.3f * (float)Math.Cos(0.1f * z); normal.Y = 1; normal.Z = -0.3f * (float)Math.Sin(0.1f * x) + 0.03f * x *(float)Math.Sin(0.1f * z); normal.Normalize(); vertices[i * number_of_cols + j].Normal = normal; } } vertexBuffer = new VertexBuffer(GraphicsDevice, VertexPositionNormalTexture.VertexDeclaration, number_of_vertices, BufferUsage.WriteOnly); vertexBuffer.SetData<VertexPositionNormalTexture>(vertices); }
public void OnCreateDevice(object sender, EventArgs e ) { Device dev = (Device)sender; vertexBuffer = new VertexBuffer(typeof(CustomVertex.TransformedColored ), 3, dev, 0, CustomVertex.TransformedColored.Format, Pool.Default ) ; GraphicsStream stm = vertexBuffer.Lock( 0, 0, 0 ) ; CustomVertex.TransformedColored[ ] verts = new CustomVertex.TransformedColored[ 3 ] ; verts[0].X = 150 ; verts[0].Y = 50 ; verts[0].Z = 0.5f ; verts[0].Rhw = 1 ; verts[0].Color = System.Drawing.Color.Aqua.ToArgb ( ) ; verts[1].X = 250 ; verts[1].Y = 250 ; verts[1].Z = 0.5f ; verts[1].Rhw = 1 ; verts[1].Color = System.Drawing.Color.Brown.ToArgb ( ) ; verts[2].X = 50 ; verts[2].Y = 250 ; verts[2].Z = 0.5f ; verts[2].Rhw = 1 ; verts[2].Color = System.Drawing.Color.LightPink.ToArgb ( ) ; stm.Write ( verts ) ; vertexBuffer.Unlock ( ) ; }
/// <summary> /// Allocates an empty vertex buffer. /// </summary> /// <param name="numVertices">The number of vertices to allocate.</param> public void Create(int numVertices) { if (_vertexBuffer != null) Clear(); _vertexBuffer = new VertexBuffer(GraphicsDevice.Device, PositionColoredTextured.StrideSize * numVertices, Usage.WriteOnly, PositionColoredTextured.Format, Pool.Default); ++_allocationCount; }
private void SetupVertices() { vertices = new VertexPositionColor[size.X * size.Y + 2]; vertexDeclaration = new VertexDeclaration(vertices); vertexBuffer = new VertexBuffer(CamTest.graphics.GraphicsDevice, typeof(VertexPositionColor), vertices.Length, BufferUsage.None); int vertID = 0; for (int x = 0; x < size.X + 1; x++) { vertices[vertID].Position = new Vector3(x * cellSize.X, 0f, 0f); vertices[vertID].Color = color; vertices[vertID + 1].Position = new Vector3(x * cellSize.X, 0f, size.Y * cellSize.Y); vertices[vertID + 1].Color = color; vertID += 2; } for (int y = 0; y < size.Y + 1; y++) { vertices[vertID].Position = new Vector3(0f, 0f, y * cellSize.Y); vertices[vertID].Color = color; vertices[vertID + 1].Position = new Vector3(size.X * cellSize.X, 0f, y * cellSize.Y); vertices[vertID + 1].Color = color; vertID += 2; } vertexBuffer.SetData<VertexPositionColor>(vertices); }
public Game() { InitializeComponent(); if (!InitializeDirect3D()) { return; } sounds = new GameSound(this); sounds.Victory(); font = new Microsoft.DirectX.Direct3D.Font(device, // Device we are drawing on 20, // Font height in pixels 0, // Font width in pixels or zero to match height FontWeight.Bold, // Font weight (Normal, Bold, etc.) 0, // mip levels (0 for default) false, // italics? CharacterSet.Default, // Character set to use Precision.Default, // The font precision, try some of them... FontQuality.Default, // Quality? PitchAndFamily.FamilyDoNotCare, // Pitch and family, we don't care "Arial"); // And the name of the font // To create a rectangle vertices = new VertexBuffer(typeof(CustomVertex.PositionColored), // Type of vertex 4, // How many device, // What device 0, // No special usage CustomVertex.PositionColored.Format, Pool.Managed); background = new Background(device, playingW, playingH); //draw floor ///////////////////////////////////////////////////////////// Texture floor = TextureLoader.FromFile(device, "../../../floor.jpg"); AddTexture(0, playingW / 3, 0, 1, Color.Transparent, floor, 0, 1, 0, 1); Texture poolTexture = TextureLoader.FromFile(device, "../../../pool.png"); AddBadPoly(playingW / 3, playingW / 3 * (1 + 0.5f), 0, 0.7f, Color.Transparent, poolTexture, 0, 1, 0, 1); AddTexture(playingW / 3 * (1 + 0.5f), playingW, 0, 1, Color.Transparent, floor, 0, 1, 0, 1); //create a platform AddPlatform(3.2f, 3.9f, 1.8f, 2, Color.CornflowerBlue); //create a platform AddPlatform2(playingW / 3, playingW / 3 + 0.7f, 0.8f, 1, Color.Black); AddCoins(); Texture c1 = TextureLoader.FromFile(device, "../../../candy1.png"); Texture c2 = TextureLoader.FromFile(device, "../../../candy2.png"); AddBadPoly(13.1f, 13.9f, 3.2f, 3.4f, Color.Transparent, c1, 0.3f, 1, 0.55f, 0.85f); AddBadPoly(7.1f, 8.1f, 2.2f, 2.8f, Color.Transparent, c2, 0.2f, 1, 0.05f, 0.45f); AddBadPoly(26, 27, 1.5f, 2.1f, Color.Transparent, c2, 0.2f, 1, 0.05f, 0.45f); AddObstacle(27.1f, 27.7f, 3.0f, 3.2f, Color.BlanchedAlmond); ///////////////////////////////////////////////////////////////////////////////////////////////////// ////Game AddObstacle(4, 4.2f, 1, 2.1f, Color.Coral); AddObstacle(5, 6, 1.4f, 1.6f, Color.BurlyWood); AddObstacle(5.5f, 6.5f, 3.2f, 3.4f, Color.PeachPuff); AddObstacle(8.5f, 9.5f, 2.5f, 2.7f, Color.Brown); AddObstacle(10.5f, 11.5f, 1.5f, 1.7f, Color.AliceBlue); ///add AddObstacle(11.5f, 12.5f, 2.2f, 2.4f, Color.PeachPuff); // AddObstacle(13.5f, 15f, 3.2f, 3.4f, Color.BlanchedAlmond); AddObstacle(14.5f, 15.5f, 2f, 2.2f, Color.Aqua); AddObstacle(22.5f, 24f, 3.0f, 3.2f, Color.Crimson);//red AddObstacle(29.1f, 29.9f, 2.5f, 2.8f, Color.Chocolate); Platform platform = new Platform(); platform.AddVertex(new Vector2(3.2f, 2)); platform.AddVertex(new Vector2(3.9f, 2)); platform.AddVertex(new Vector2(3.9f, 1.8f)); platform.AddVertex(new Vector2(3.2f, 1.8f)); platform.Color = Color.Black; world.Add(platform); ///OBJECT1 Texture weird_texture = TextureLoader.FromFile(device, "../../../green.jpg"); Weird wd = new Weird(); wd.Tex = weird_texture; //triangle offset=0 wd.AddVertex(new Vector2(1.5f, 1.1f)); wd.AddVertex(new Vector2(1f, 1.5f)); wd.AddVertex(new Vector2(2f, 1.5f)); world.Add(wd); ///OBJECT2 Texture texture = TextureLoader.FromFile(device, "../../../stone08.bmp"); PolygonTextured pt = new PolygonTextured(); pt.Tex = texture; pt.AddVertex(new Vector2(17.5f, 1f)); pt.AddTex(new Vector2(0, 0)); pt.AddVertex(new Vector2(17f, 1.5f)); pt.AddTex(new Vector2(0, 1)); pt.AddVertex(new Vector2(19f, 1.5f)); pt.AddTex(new Vector2(1, 1)); pt.AddVertex(new Vector2(18.5f, 1f)); pt.AddTex(new Vector2(1, 0)); pt.Color = Color.Transparent; world.Add(pt); ///OBJECT3 Texture texture3 = TextureLoader.FromFile(device, "../../../brown.jpg"); PolygonTextured pt3 = new PolygonTextured(); pt3.Tex = texture3; pt3.AddVertex(new Vector2(20, 2.7f)); //A pt3.AddTex(new Vector2(0, 1)); pt3.AddVertex(new Vector2(21, 2.7f)); //B pt3.AddTex(new Vector2(0.5f, 0)); pt3.AddVertex(new Vector2(21, 2.5f)); //C pt3.AddTex(new Vector2(1, 0.5f)); pt3.AddVertex(new Vector2((20 + 21) / 2.0f, 2)); //D pt3.AddTex(new Vector2(1, 1)); pt3.AddVertex(new Vector2(20, 2.5f)); pt3.AddTex(new Vector2(0, 0.5f)); world.Add(pt3); ///Object4 Texture texture4 = TextureLoader.FromFile(device, "../../../green.jpg"); PolygonTextured pt4 = new PolygonTextured(); pt4.Tex = texture4; pt4.AddVertex(new Vector2(5.375f, 1f)); pt4.AddTex(new Vector2(1, 0.5f)); pt4.AddVertex(new Vector2(5f, 1.2f)); pt4.AddTex(new Vector2(0, 0)); pt4.AddVertex(new Vector2(5.5f, 1.4f)); pt4.AddTex(new Vector2(0, 0.5f)); pt4.AddVertex(new Vector2(5.5f, 1.2f)); pt4.AddTex(new Vector2(0.5f, 0)); pt4.AddVertex(new Vector2(6f, 1.2f)); pt4.AddTex(new Vector2(0.5f, 0.5f)); pt4.AddVertex(new Vector2(5.625f, 1f)); pt4.AddTex(new Vector2(0.5f, 1)); world.Add(pt4); Texture spritetexture = TextureLoader.FromFile(device, "../../../guy8.bmp"); player.Transparent = true; player.P = new Vector2(0.5f, 1); player.Tex = spritetexture; player.AddVertex(new Vector2(-0.2f, 0)); player.AddTex(new Vector2(0, 1)); player.AddVertex(new Vector2(-0.2f, 1)); player.AddTex(new Vector2(0, 0)); player.AddVertex(new Vector2(0.2f, 1)); player.AddTex(new Vector2(0.125f, 0)); player.AddVertex(new Vector2(0.2f, 0)); player.AddTex(new Vector2(0.125f, 1)); player.Color = Color.Transparent; // Determine the last time stopwatch.Start(); lastTime = stopwatch.ElapsedMilliseconds; }
public CSkybox(GraphicsDevice p_device) { device = p_device; Vector3 p_min = new Vector3(-1, -1, -1); Vector3 p_max = new Vector3(1, 1, 1); VertexPositionTexture[] vertices = new VertexPositionTexture[36]; // abajo vertices[0].Position = new Vector3(p_min.X, p_min.Y, p_min.Z); vertices[0].TextureCoordinate = new Vector2(0, 0); vertices[1].Position = new Vector3(p_max.X, p_min.Y, p_min.Z); vertices[1].TextureCoordinate = new Vector2(0, 1); vertices[2].Position = new Vector3(p_max.X, p_min.Y, p_max.Z); vertices[2].TextureCoordinate = new Vector2(1, 1); vertices[3].Position = new Vector3(p_min.X, p_min.Y, p_min.Z); vertices[3].TextureCoordinate = new Vector2(0, 0); vertices[4].Position = new Vector3(p_max.X, p_min.Y, p_max.Z); vertices[4].TextureCoordinate = new Vector2(1, 1); vertices[5].Position = new Vector3(p_min.X, p_min.Y, p_max.Z); vertices[5].TextureCoordinate = new Vector2(1, 0); // arriba for (int i = 0; i < 6; ++i) { vertices[6 + i].Position = vertices[i].Position; vertices[6 + i].Position.Y = p_max.Y; vertices[6 + i].TextureCoordinate = vertices[i].TextureCoordinate; } //izquierda vertices[12].Position = new Vector3(p_min.X, p_min.Y, p_min.Z); vertices[12].TextureCoordinate = new Vector2(1, 1); vertices[13].Position = new Vector3(p_min.X, p_min.Y, p_max.Z); vertices[13].TextureCoordinate = new Vector2(0, 1); vertices[14].Position = new Vector3(p_min.X, p_max.Y, p_max.Z); vertices[14].TextureCoordinate = new Vector2(0, 0); vertices[15].Position = new Vector3(p_min.X, p_min.Y, p_min.Z); vertices[15].TextureCoordinate = new Vector2(1, 1); vertices[16].Position = new Vector3(p_min.X, p_max.Y, p_max.Z); vertices[16].TextureCoordinate = new Vector2(0, 0); vertices[17].Position = new Vector3(p_min.X, p_max.Y, p_min.Z); vertices[17].TextureCoordinate = new Vector2(1, 0); //derecha for (int i = 0; i < 6; ++i) { vertices[18 + i].Position = vertices[12 + i].Position; vertices[18 + i].Position.X = p_max.X; vertices[18 + i].TextureCoordinate = vertices[12 + i].TextureCoordinate; vertices[18 + i].TextureCoordinate.X = 1 - vertices[18 + i].TextureCoordinate.X; } //adelante vertices[24].Position = new Vector3(p_min.X, p_min.Y, p_max.Z); vertices[24].TextureCoordinate = new Vector2(1, 1); vertices[25].Position = new Vector3(p_max.X, p_min.Y, p_max.Z); vertices[25].TextureCoordinate = new Vector2(0, 1); vertices[26].Position = new Vector3(p_min.X, p_max.Y, p_max.Z); vertices[26].TextureCoordinate = new Vector2(1, 0); vertices[27].Position = new Vector3(p_max.X, p_min.Y, p_max.Z); vertices[27].TextureCoordinate = new Vector2(0, 1); vertices[28].Position = new Vector3(p_min.X, p_max.Y, p_max.Z); vertices[28].TextureCoordinate = new Vector2(1, 0); vertices[29].Position = new Vector3(p_max.X, p_max.Y, p_max.Z); vertices[29].TextureCoordinate = new Vector2(0, 0); //atras for (int i = 0; i < 6; ++i) { vertices[30 + i].Position = vertices[24 + i].Position; vertices[30 + i].Position.Z = p_min.Z; vertices[30 + i].TextureCoordinate = vertices[24 + i].TextureCoordinate; vertices[30 + i].TextureCoordinate.X = 1 - vertices[24 + i].TextureCoordinate.X; } VertexBuffer = new VertexBuffer(device, VertexPositionTexture.VertexDeclaration, 36, BufferUsage.WriteOnly); VertexBuffer.SetData(vertices); texture[0] = CTextureLoader.Load(device, CBspFile.tex_folder + "skybox\\assaultdn.tga"); texture[1] = CTextureLoader.Load(device, CBspFile.tex_folder + "skybox\\assaultup.tga"); texture[2] = CTextureLoader.Load(device, CBspFile.tex_folder + "skybox\\assaultlf.tga"); texture[3] = CTextureLoader.Load(device, CBspFile.tex_folder + "skybox\\assaultrt.tga"); texture[4] = CTextureLoader.Load(device, CBspFile.tex_folder + "skybox\\assaultft.tga"); texture[5] = CTextureLoader.Load(device, CBspFile.tex_folder + "skybox\\assaultbk.tga"); }
protected void GenerateGeometry() { // Create vertices numVertices = numRows * numCols; numIndices = 3 * ((numRows - 1) * (numCols - 1) * 2); VertexPosNormTex[] vertices = new VertexPosNormTex[numVertices]; float halfWidth = (float)(numRows - 1) * spacing * 0.5f; float halfDepth = (float)(numCols - 1) * spacing * 0.5f; float du = 1.0f / (numRows - 1); float dv = 1.0f / (numCols - 1); for (int i = 0; i < numRows; i++) { float z = (halfDepth - i * spacing) * -1.0f; for (int j = 0; j < numCols; j++) { float x = -halfWidth + j * spacing; float y = heightValues[i * numCols + j]; vertices[i * numCols + j].pos = new Vector3(x, y, z); vertices[i * numCols + j].norm = Vector3.Zero; vertices[i * numCols + j].tex.X = du * j; vertices[i * numCols + j].tex.Y = dv * i; } } // Create indices int[] indices = new int[numIndices]; int k = 0; for (int i = 0; i < numCols - 1; i++) { for (int j = 0; j < numRows - 1; j++) { indices[k] = i * numRows + j; indices[k + 1] = i * numRows + j + 1; indices[k + 2] = (i + 1) * numRows + j; indices[k + 3] = (i + 1) * numRows + j; indices[k + 4] = i * numRows + j + 1; indices[k + 5] = (i + 1) * numRows + j + 1; k += 6; } } // Calculate vertex normals for (int i = 0; i < numIndices; i += 3) { Vector3 v0 = vertices[indices[i]].pos; Vector3 v1 = vertices[indices[i + 1]].pos; Vector3 v2 = vertices[indices[i + 2]].pos; Vector3 e0 = v1 - v0; Vector3 e1 = v2 - v0; Vector3 norm = Vector3.Cross(e1, e0); norm.Normalize(); // Update vertex values vertices[indices[i]].norm += norm; vertices[indices[i + 1]].norm += norm; vertices[indices[i + 2]].norm += norm; } // Normalize all vectors normalValues = new Vector3[numVertices]; for (int i = 0; i < numVertices; i++) { vertices[i].norm.Normalize(); normalValues[i] = vertices[i].norm; } // Create Vertex Buffer vertexBuffer = new VertexBuffer(device, VertexPosNormTex.VertexLayout, numVertices, BufferUsage.WriteOnly); vertexBuffer.SetData(vertices); // Create Index Buffer indexBuffer = new IndexBuffer(device, IndexElementSize.ThirtyTwoBits, numIndices, BufferUsage.WriteOnly); indexBuffer.SetData(indices); }
public Magnet(GraphicsDevice d, ContentManager Content) { device = d; // Vertex generation code for a bar magnet (rectangular prism) vertBuffer = new VertexBuffer(device, VertexPositionPolarity.VertexDeclaration, 8, BufferUsage.WriteOnly); VertexPositionPolarity[] verts = new VertexPositionPolarity[8]; verts[0] = new VertexPositionPolarity(new Vector3(-0.2f, -0.2f, -1.0f), 1); verts[1] = new VertexPositionPolarity(new Vector3(0.2f, -0.2f, -1.0f), 1); verts[2] = new VertexPositionPolarity(new Vector3(0.2f, 0.2f, -1.0f), 1); verts[3] = new VertexPositionPolarity(new Vector3(-0.2f, 0.2f, -1.0f), 1); verts[4] = new VertexPositionPolarity(new Vector3(-0.2f, -0.2f, 1.0f), -1); verts[5] = new VertexPositionPolarity(new Vector3(0.2f, -0.2f, 1.0f), -1); verts[6] = new VertexPositionPolarity(new Vector3(0.2f, 0.2f, 1.0f), -1); verts[7] = new VertexPositionPolarity(new Vector3(-0.2f, 0.2f, 1.0f), -1); vertBuffer.SetData(verts); indexBuffer = new IndexBuffer(device, IndexElementSize.SixteenBits, 36, BufferUsage.WriteOnly); short[] indices = new short[36]; // Back side indices[0] = 0; indices[1] = 2; indices[2] = 3; indices[3] = 0; indices[4] = 1; indices[5] = 2; // Front side indices[6] = 4; indices[7] = 7; indices[8] = 6; indices[9] = 4; indices[10] = 6; indices[11] = 5; // Right side indices[12] = 5; indices[13] = 6; indices[14] = 2; indices[15] = 5; indices[16] = 2; indices[17] = 1; // Left side indices[18] = 0; indices[19] = 3; indices[20] = 7; indices[21] = 0; indices[22] = 7; indices[23] = 4; // Top side indices[24] = 7; indices[25] = 3; indices[26] = 2; indices[27] = 7; indices[28] = 2; indices[29] = 6; // Bottom side indices[30] = 0; indices[31] = 4; indices[32] = 5; indices[33] = 0; indices[34] = 5; indices[35] = 1; indexBuffer.SetData(indices); magnetEffect = Content.Load <Effect>("magnet"); }
public void Initialize(GraphicsDevice graphicsDevice) { _decalBlend = new BlendState() { AlphaDestinationBlend = Blend.One, AlphaSourceBlend = Blend.Zero, ColorDestinationBlend = Blend.InverseSourceAlpha, ColorSourceBlend = Blend.SourceAlpha, }; VertexPositionColor[] verts = new VertexPositionColor[8]; Vector3 a = -Vector3.One; Vector3 b = Vector3.One; Color color = Color.White; Color colorUpper = new Color(0, 255, 0, 255); verts[0] = new VertexPositionColor(new Vector3(a.X, a.Y, a.Z), color); verts[1] = new VertexPositionColor(new Vector3(b.X, a.Y, a.Z), color); verts[2] = new VertexPositionColor(new Vector3(a.X, b.Y, a.Z), color); verts[3] = new VertexPositionColor(new Vector3(b.X, b.Y, a.Z), color); verts[4] = new VertexPositionColor(new Vector3(a.X, a.Y, b.Z), colorUpper); verts[5] = new VertexPositionColor(new Vector3(b.X, a.Y, b.Z), colorUpper); verts[6] = new VertexPositionColor(new Vector3(a.X, b.Y, b.Z), colorUpper); verts[7] = new VertexPositionColor(new Vector3(b.X, b.Y, b.Z), colorUpper); short[] Indices = new short[24]; Indices[0] = 0; Indices[1] = 1; Indices[2] = 1; Indices[3] = 3; Indices[4] = 3; Indices[5] = 2; Indices[6] = 2; Indices[7] = 0; Indices[8] = 4; Indices[9] = 5; Indices[10] = 5; Indices[11] = 7; Indices[12] = 7; Indices[13] = 6; Indices[14] = 6; Indices[15] = 4; Indices[16] = 0; Indices[17] = 4; Indices[18] = 1; Indices[19] = 5; Indices[20] = 2; Indices[21] = 6; Indices[22] = 3; Indices[23] = 7; //short[] Indices2 = new short[36]; short[] Indices2 = new short[] { 0, 4, 1, 1, 4, 5, 1, 5, 3, 3, 5, 7, 2, 3, 7, 7, 6, 2, 2, 6, 0, 0, 6, 4, 5, 4, 7, 7, 4, 6, 2, 0, 1, 1, 3, 2 }; _vertexBuffer = new VertexBuffer(graphicsDevice, VertexPositionColor.VertexDeclaration, 8, BufferUsage.WriteOnly); _indexBufferCage = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, 24, BufferUsage.WriteOnly); _indexBufferCube = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, 36, BufferUsage.WriteOnly); _vertexBuffer.SetData(verts); _indexBufferCage.SetData(Indices); _indexBufferCube.SetData(Indices2); }
/// <summary> /// Draws a filled Circle /// </summary> /// <param name="x">Position X</param> /// <param name="y">Position Y</param> /// <param name="rad">Radius</param> /// <param name="rotate">Rotation 0 - 360</param> /// <param name="type">Circle Type</param> /// <param name="smoothing">Smooth Antialiasing</param> /// <param name="resolution">Real smooth value</param> /// <param name="color">Color</param> public static void DrawCircleFilled(float x, float y, float rad, float rotate, CircleType type, bool smoothing, int resolution, Color color) { VertexBuffer vertices = new VertexBuffer( Drawing.Direct3DDevice, Utilities.SizeOf <Vector4>() * 2 * (resolution + 4), Usage.WriteOnly, VertexFormat.Diffuse | VertexFormat.PositionRhw, Pool.Default); double angle = rotate * Math.PI / 180d; double pi = 0.0d; if (type == CircleType.Full) { pi = Math.PI; // Full circle } if (type == CircleType.Half) { pi = Math.PI / 2d; // 1/2 circle } if (type == CircleType.Quarter) { pi = Math.PI / 4d; // 1/4 circle } List <Vector4> data = new List <Vector4>(new [] { new Vector4(x, y, 0f, 1f), color.ToVector4() }); for (int i = 1; i < resolution + 4; i++) { float x1 = (float)(x - rad * Math.Cos(pi * ((i - 1) / (resolution / 2.0f)))); float y1 = (float)(y - rad * Math.Sin(pi * ((i - 1) / (resolution / 2.0f)))); data.AddRange(new[] { new Vector4(x1, y1, 0f, 1.0f), color.ToVector4() }); } // Rotate matrix int res = 2 * resolution + 4; for (int i = 0; i < res; i = i + 2) { data[i] = new Vector4((float)(x + Math.Cos(angle) * (data[i].X - x) - Math.Sin(angle) * (data[i].Y - y)), (float)(y + Math.Sin(angle) * (data[i].X - x) + Math.Cos(angle) * (data[i].Y - y)), data[i].Z, data[i].W); } vertices.Lock(0, Utilities.SizeOf <Vector4>() * 2 * (resolution + 4), LockFlags.None).WriteRange(data.ToArray()); vertices.Unlock(); VertexElement[] vertexElements = { new VertexElement( 0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement( 0, 16, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; VertexDeclaration vertexDeclaration = new VertexDeclaration(Drawing.Direct3DDevice, vertexElements); if (smoothing) { Drawing.Direct3DDevice.SetRenderState(RenderState.MultisampleAntialias, true); Drawing.Direct3DDevice.SetRenderState(RenderState.AntialiasedLineEnable, true); } else { Drawing.Direct3DDevice.SetRenderState(RenderState.MultisampleAntialias, false); Drawing.Direct3DDevice.SetRenderState(RenderState.AntialiasedLineEnable, false); } var olddec = Drawing.Direct3DDevice.VertexDeclaration; Drawing.Direct3DDevice.SetStreamSource(0, vertices, 0, Utilities.SizeOf <Vector4>() * 2); Drawing.Direct3DDevice.VertexDeclaration = vertexDeclaration; Drawing.Direct3DDevice.DrawPrimitives(PrimitiveType.TriangleFan, 0, resolution); Drawing.Direct3DDevice.VertexDeclaration = olddec; vertexDeclaration.Dispose(); vertices.Dispose(); }
public void BuildInstanceBuffer() { InstanceBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexInstanceEnv), Instances_Env.Count, BufferUsage.WriteOnly); InstanceBuffer.SetData(Instances_Env.ToArray()); }
public void loadHeightmap(string heightmapPath, float pscaleXZ, float pscaleY, Vector3 center) { scaleXZ = pscaleXZ; scaleY = pscaleY; Device d3dDevice = GuiController.Instance.D3dDevice; this.center = center; //Dispose de VertexBuffer anterior, si habia if (vbTerrain != null && !vbTerrain.Disposed) { vbTerrain.Dispose(); } //cargar heightmap heightmapData = loadHeightMap(d3dDevice, heightmapPath); float width = (float)heightmapData.GetLength(0); float length = (float)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.PositionTextured), totalVertices, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); //Cargar vertices int dataIdx = 0; CustomVertex.PositionTextured[] data = new CustomVertex.PositionTextured[totalVertices]; center.X = center.X * scaleXZ - (width / 2) * scaleXZ; center.Y = center.Y * scaleY; center.Z = center.Z * scaleXZ - (length / 2) * scaleXZ; if (torus) { float di = width * ki; float dj = length * kj; for (int i = 0; i < width * ki; i++) { for (int j = 0; j < length * kj; j++) { int ri = i % (int)width; int rj = j % (int)length; int ri1 = (i + 1) % (int)width; int rj1 = (j + 1) % (int)length; Vector3 v1, v2, v3, v4; { float r = radio_2 + heightmapData[ri, rj] * scaleY; float s = 2f * (float)Math.PI * j / dj; float t = -(float)Math.PI * i / di; float x = (float)Math.Cos(s) * (radio_1 + r * (float)Math.Cos(t)); float z = (float)Math.Sin(s) * (radio_1 + r * (float)Math.Cos(t)); float y = r * (float)Math.Sin(t); v1 = new Vector3(x, y, z); } { float r = radio_2 + heightmapData[ri, rj1] * scaleY; float s = 2f * (float)Math.PI * (j + 1) / dj; float t = -(float)Math.PI * i / di; float x = (float)Math.Cos(s) * (radio_1 + r * (float)Math.Cos(t)); float z = (float)Math.Sin(s) * (radio_1 + r * (float)Math.Cos(t)); float y = r * (float)Math.Sin(t); v2 = new Vector3(x, y, z); } { float r = radio_2 + heightmapData[ri1, rj] * scaleY; float s = 2f * (float)Math.PI * j / dj; float t = -(float)Math.PI * (i + 1) / di; float x = (float)Math.Cos(s) * (radio_1 + r * (float)Math.Cos(t)); float z = (float)Math.Sin(s) * (radio_1 + r * (float)Math.Cos(t)); float y = r * (float)Math.Sin(t); v3 = new Vector3(x, y, z); } { float r = radio_2 + heightmapData[ri1, rj1] * scaleY; float s = 2f * (float)Math.PI * (j + 1) / dj; float t = -(float)Math.PI * (i + 1) / di; float x = (float)Math.Cos(s) * (radio_1 + r * (float)Math.Cos(t)); float z = (float)Math.Sin(s) * (radio_1 + r * (float)Math.Cos(t)); float y = r * (float)Math.Sin(t); v4 = new Vector3(x, y, z); } //Coordendas de textura Vector2 t1 = new Vector2(ftex * i / width, ftex * j / length); Vector2 t2 = new Vector2(ftex * i / width, ftex * (j + 1) / length); Vector2 t3 = new Vector2(ftex * (i + 1) / width, ftex * j / length); Vector2 t4 = new Vector2(ftex * (i + 1) / width, ftex * (j + 1) / length); //Cargar triangulo 1 data[dataIdx] = new CustomVertex.PositionTextured(v1, t1.X, t1.Y); data[dataIdx + 1] = new CustomVertex.PositionTextured(v2, t2.X, t2.Y); data[dataIdx + 2] = new CustomVertex.PositionTextured(v4, t4.X, t4.Y); //Cargar triangulo 2 data[dataIdx + 3] = new CustomVertex.PositionTextured(v1, t1.X, t1.Y); data[dataIdx + 4] = new CustomVertex.PositionTextured(v4, t4.X, t4.Y); data[dataIdx + 5] = new CustomVertex.PositionTextured(v3, t3.X, t3.Y); dataIdx += 6; } } } else { for (int i = 0; i < width - 1; i++) { for (int j = 0; j < length - 1; j++) { //Vertices Vector3 v1 = new Vector3(center.X + i * scaleXZ, center.Y + heightmapData[i, j] * scaleY, center.Z + j * scaleXZ); Vector3 v2 = new Vector3(center.X + i * scaleXZ, center.Y + heightmapData[i, j + 1] * scaleY, center.Z + (j + 1) * scaleXZ); Vector3 v3 = new Vector3(center.X + (i + 1) * scaleXZ, center.Y + heightmapData[i + 1, j] * scaleY, center.Z + j * scaleXZ); Vector3 v4 = new Vector3(center.X + (i + 1) * scaleXZ, center.Y + heightmapData[i + 1, j + 1] * scaleY, center.Z + (j + 1) * scaleXZ); //Coordendas de textura Vector2 t1 = new Vector2(ftex * i / width, ftex * j / length); Vector2 t2 = new Vector2(ftex * i / width, ftex * (j + 1) / length); Vector2 t3 = new Vector2(ftex * (i + 1) / width, ftex * j / length); Vector2 t4 = new Vector2(ftex * (i + 1) / width, ftex * (j + 1) / length); //Cargar triangulo 1 data[dataIdx] = new CustomVertex.PositionTextured(v1, t1.X, t1.Y); data[dataIdx + 1] = new CustomVertex.PositionTextured(v2, t2.X, t2.Y); data[dataIdx + 2] = new CustomVertex.PositionTextured(v4, t4.X, t4.Y); //Cargar triangulo 2 data[dataIdx + 3] = new CustomVertex.PositionTextured(v1, t1.X, t1.Y); data[dataIdx + 4] = new CustomVertex.PositionTextured(v4, t4.X, t4.Y); data[dataIdx + 5] = new CustomVertex.PositionTextured(v3, t3.X, t3.Y); dataIdx += 6; } } } vbTerrain.SetData(data, 0, LockFlags.None); }
public void Clear() { m_VertexBuffer = null; m_IndexBuffer = null; }
private void GenerateCommonGeometryCube() { VertexPositionTexture[] _vertices = new VertexPositionTexture[24]; #region filling vertices _vertices[0].Position = new Vector3(-1, 1, -1); _vertices[0].TextureCoordinate = new Vector2(0, 0); _vertices[1].Position = new Vector3(1, 1, -1); _vertices[1].TextureCoordinate = new Vector2(1, 0); _vertices[2].Position = new Vector3(-1, 1, 1); _vertices[2].TextureCoordinate = new Vector2(0, 1); _vertices[3].Position = new Vector3(1, 1, 1); _vertices[3].TextureCoordinate = new Vector2(1, 1); _vertices[4].Position = new Vector3(-1, -1, 1); _vertices[4].TextureCoordinate = new Vector2(0, 0); _vertices[5].Position = new Vector3(1, -1, 1); _vertices[5].TextureCoordinate = new Vector2(1, 0); _vertices[6].Position = new Vector3(-1, -1, -1); _vertices[6].TextureCoordinate = new Vector2(0, 1); _vertices[7].Position = new Vector3(1, -1, -1); _vertices[7].TextureCoordinate = new Vector2(1, 1); _vertices[8].Position = new Vector3(-1, 1, -1); _vertices[8].TextureCoordinate = new Vector2(0, 0); _vertices[9].Position = new Vector3(-1, 1, 1); _vertices[9].TextureCoordinate = new Vector2(1, 0); _vertices[10].Position = new Vector3(-1, -1, -1); _vertices[10].TextureCoordinate = new Vector2(0, 1); _vertices[11].Position = new Vector3(-1, -1, 1); _vertices[11].TextureCoordinate = new Vector2(1, 1); _vertices[12].Position = new Vector3(-1, 1, 1); _vertices[12].TextureCoordinate = new Vector2(0, 0); _vertices[13].Position = new Vector3(1, 1, 1); _vertices[13].TextureCoordinate = new Vector2(1, 0); _vertices[14].Position = new Vector3(-1, -1, 1); _vertices[14].TextureCoordinate = new Vector2(0, 1); _vertices[15].Position = new Vector3(1, -1, 1); _vertices[15].TextureCoordinate = new Vector2(1, 1); _vertices[16].Position = new Vector3(1, 1, 1); _vertices[16].TextureCoordinate = new Vector2(0, 0); _vertices[17].Position = new Vector3(1, 1, -1); _vertices[17].TextureCoordinate = new Vector2(1, 0); _vertices[18].Position = new Vector3(1, -1, 1); _vertices[18].TextureCoordinate = new Vector2(0, 1); _vertices[19].Position = new Vector3(1, -1, -1); _vertices[19].TextureCoordinate = new Vector2(1, 1); _vertices[20].Position = new Vector3(1, 1, -1); _vertices[20].TextureCoordinate = new Vector2(0, 0); _vertices[21].Position = new Vector3(-1, 1, -1); _vertices[21].TextureCoordinate = new Vector2(1, 0); _vertices[22].Position = new Vector3(1, -1, -1); _vertices[22].TextureCoordinate = new Vector2(0, 1); _vertices[23].Position = new Vector3(-1, -1, -1); _vertices[23].TextureCoordinate = new Vector2(1, 1); #endregion geometryBuffer = new VertexBuffer(GraphicsDevice, VertexPositionTexture.VertexDeclaration, 24, BufferUsage.WriteOnly); geometryBuffer.SetData(_vertices); #region filling indices Int16[] _indices = new Int16[36]; _indices[0] = 0; _indices[1] = 1; _indices[2] = 2; _indices[3] = 1; _indices[4] = 3; _indices[5] = 2; _indices[6] = 4; _indices[7] = 5; _indices[8] = 6; _indices[9] = 5; _indices[10] = 7; _indices[11] = 6; _indices[12] = 8; _indices[13] = 9; _indices[14] = 10; _indices[15] = 9; _indices[16] = 11; _indices[17] = 10; _indices[18] = 12; _indices[19] = 13; _indices[20] = 14; _indices[21] = 13; _indices[22] = 15; _indices[23] = 14; _indices[24] = 16; _indices[25] = 17; _indices[26] = 18; _indices[27] = 17; _indices[28] = 19; _indices[29] = 18; _indices[30] = 20; _indices[31] = 21; _indices[32] = 22; _indices[33] = 21; _indices[34] = 23; _indices[35] = 22; #endregion indexBuffer = new IndexBuffer(GraphicsDevice, typeof(Int16), 36, BufferUsage.WriteOnly); indexBuffer.SetData(_indices); }
public static void SaveVertexBuffer(FSHP fshp) { VertexBuffer buffer = new VertexBuffer(); buffer.Attributes = new ResDict <VertexAttrib>(); VertexBufferHelper helper = new VertexBufferHelper(buffer, Syroot.BinaryData.ByteOrder.BigEndian); List <VertexBufferHelperAttrib> atrib = new List <VertexBufferHelperAttrib>(); fshp.UpdateVertices(); foreach (FSHP.VertexAttribute att in fshp.vertexAttributes) { if (att.Name == "_p0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.verts.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_n0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.norms.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_u0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.uv0.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_u1") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.uv1.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_u2") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.uv2.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_w0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.weights.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_i0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.boneInd.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_b0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.bitans.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_t0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.tans.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } if (att.Name == "_c0") { VertexBufferHelperAttrib vert = new VertexBufferHelperAttrib(); vert.Name = att.Name; vert.Data = fshp.colors.ToArray(); vert.Format = att.SetTypeWiiU(att.Format); atrib.Add(vert); } } if (atrib.Count == 0) { MessageBox.Show("Attributes are empty?"); return; } helper.Attributes = atrib; fshp.VertexBufferU = helper.ToVertexBuffer(); }
/// <summary> /// Draw the vertices group as primitives, using an optional index buffer (indices) and a <see cref="StreamFrequency"/> object to specify Hardware Instancing information (Shader Model 3 and Windows Only) /// </summary> /// <param name="state"></param> /// <param name="indices">(optional) indices to use during drawing</param> /// <param name="primitiveType">Primitive type to draw, eg PrimitiveType.TriangleList</param> /// <param name="frequency">(optional) <see cref="StreamFrequency"/> setting the shader model 3 instance frequency data (used for hardware instancing)</param> /// <param name="primitveCount">The number of primitives to draw</param> /// <param name="startIndex">The start index in the index buffer (defaults to the first index - 0)</param> /// <param name="vertexOffset">Starting offset into the vertex buffer (defaults to the first vertex - 0)</param> /// <remarks></remarks> public void Draw(DrawState state, IIndices indices, PrimitiveType primitiveType, StreamFrequency frequency, int primitveCount, int startIndex, int vertexOffset) { if (frequency != null && !state.SupportsHardwareInstancing) { throw new InvalidOperationException("Only windows devices supporting Shader Model 3.0 or better to can use hardware instancing. Check DrawState.SupportsHardwareInstancing"); } #if XBOX360 if (frequency != null) { #if DEBUG if (frequency.layout != StreamFrequency.DataLayout.Stream0Geometry_Stream1InstanceData) { throw new InvalidOperationException("Only StreamFrequency DataLayout of Stream0Geometry_Stream1InstanceData is emulated on the xbox360"); } if (primitveCount != int.MaxValue || startIndex != 0 || vertexOffset != 0) { throw new ArgumentException("Only default values for primitiveCount, startIndex and vertexOffset may be used when emulating instancing on the xbox"); } if (primitiveType == PrimitiveType.TriangleFan || primitiveType == PrimitiveType.TriangleStrip || primitiveType == PrimitiveType.LineStrip) { throw new ArgumentException("Only Primitive List Types (eg TriangleList) are supported as a primitiveType when emulating instancing on the xbox"); } #endif if (indices != null) { ((IDeviceIndexBuffer)indices).AllocateForInstancing(state); } } #endif GraphicsDevice device = state.graphics; IDeviceIndexBuffer devib = indices as IDeviceIndexBuffer; IndexBuffer ib = null; if (devib != null) { ib = devib.GetIndexBuffer(state); } if (decl == null) { decl = ((IDeviceVertexBuffer)this).GetVertexDeclaration(state.Application); } state.VertexDeclaration = decl; #if DEBUG state.ValidateVertexDeclarationForShader(decl, null); #endif int vertices = 0; for (int i = 0; i < buffers.Length; i++) { IDeviceVertexBuffer dev = buffers[i] as IDeviceVertexBuffer; if (dev != null) { state.SetStream(i, dev.GetVertexBuffer(state), offsets[i], buffers[i].Stride); } else { state.SetStream(i, null, 0, 0); } if (i == 0) { vertices = buffers[i].Count; } else if (frequency == null) { vertices = Math.Min(buffers[i].Count, vertices); } } state.IndexBuffer = ib; if (ib != null) { vertices = indices.Count; } int primitives = 0; switch (primitiveType) { case PrimitiveType.LineList: primitives = vertices / 2; break; case PrimitiveType.LineStrip: primitives = vertices - 1; break; case PrimitiveType.PointList: primitives = vertices; break; case PrimitiveType.TriangleList: primitives = vertices / 3; break; case PrimitiveType.TriangleFan: case PrimitiveType.TriangleStrip: primitives = vertices - 2; break; } int vertexCount = 0; if (indices != null) { vertexCount = indices.MaxIndex + 1; } else { switch (primitiveType) { case PrimitiveType.LineStrip: vertexCount = primitives * 2; break; case PrimitiveType.PointList: case PrimitiveType.LineList: case PrimitiveType.TriangleList: vertexCount = vertices; break; case PrimitiveType.TriangleFan: case PrimitiveType.TriangleStrip: vertexCount = primitives * 3; break; } } state.ApplyRenderStateChanges(vertexCount); #if DEBUG int instances = 1; #endif #if !XBOX360 if (frequency != null && frequency.frequency.Length >= this.buffers.Length) { #if DEBUG if (frequency.indexFrequency.Length > 0) { System.Threading.Interlocked.Increment(ref state.Application.currentFrame.InstancesDrawBatchCount); state.Application.currentFrame.InstancesDrawn += frequency.indexFrequency[0]; instances = frequency.indexFrequency[0]; } #endif for (int i = 0; i < this.buffers.Length; i++) { VertexStream vs = device.Vertices[i]; if (frequency.frequency[i] != 0) { vs.SetFrequency(frequency.frequency[i]); } if (frequency.indexFrequency[i] != 0) { vs.SetFrequencyOfIndexData(frequency.indexFrequency[i]); } if (frequency.dataFrequency[i] != 0) { vs.SetFrequencyOfInstanceData(frequency.dataFrequency[i]); } } } #endif if (primitveCount != int.MaxValue) { if (primitveCount > primitives || primitveCount <= 0) { throw new ArgumentException("primitiveCount"); } } else { primitveCount = primitives; } #if DEBUG state.CalcBoundTextures(); #endif //it is possible to have the debug runtime throw an exception here when using instancing, //as it thinks stream1 doesn't have enough data. //This is most common with sprite groups (however sprite groups will use shader-instancing with small groups) //eg, drawing a single instance requires only 64bytes in stream1, yet the triangle count could be very large //this makes the debug runtime think that stream1 doesn't have enough data if (ib != null) { #if DEBUG System.Threading.Interlocked.Increment(ref state.Application.currentFrame.DrawIndexedPrimitiveCallCount); #endif #if XBOX360 if (frequency != null) { int repeats = frequency.RepeatCount; #if DEBUG System.Threading.Interlocked.Increment(ref state.Application.currentFrame.InstancesDrawBatchCount); state.Application.currentFrame.InstancesDrawn += frequency.indexFrequency[0]; instances = repeats; #endif int maxInstances = ((IDeviceIndexBuffer)indices).MaxInstances; int offset = 0; VertexBuffer vb = ((IDeviceVertexBuffer)buffers[1]).GetVertexBuffer(state); while (repeats - offset > 0) { if (offset != 0) { //read the next set of instances state.SetStream(1, vb, offsets[1] + 64 * offset, buffers[1].Stride); } int count = Math.Min(repeats - offset, maxInstances); device.DrawIndexedPrimitives(primitiveType, vertexOffset, indices.MinIndex, ((indices.MaxIndex) + 1) - indices.MinIndex - vertexOffset, startIndex, primitveCount * count); offset += count; } } else #endif device.DrawIndexedPrimitives(primitiveType, vertexOffset, indices.MinIndex, (indices.MaxIndex - indices.MinIndex) + 1 - vertexOffset, startIndex, primitveCount); } else { #if DEBUG System.Threading.Interlocked.Increment(ref state.Application.currentFrame.DrawPrimitivesCallCount); #endif #if XBOX360 if (frequency != null) { int repeats = frequency.RepeatCount; int maxInstances = ((IDeviceIndexBuffer)indices).MaxInstances; int offset = 0; VertexBuffer vb = ((IDeviceVertexBuffer)buffers[1]).GetVertexBuffer(state); while (repeats - offset > 0) { if (offset != 0) { //read the next set of instances state.SetStream(1, vb, offsets[1] + 64 * offset, buffers[1].Stride); } int count = Math.Min(repeats - offset, maxInstances); device.DrawPrimitives(primitiveType, vertexOffset, primitveCount * count); offset += count; } } else #endif device.DrawPrimitives(primitiveType, vertexOffset, primitveCount); } #if DEBUG switch (primitiveType) { case PrimitiveType.LineList: case PrimitiveType.LineStrip: state.Application.currentFrame.LinesDrawn += primitives * instances; break; case PrimitiveType.PointList: state.Application.currentFrame.PointsDrawn += primitives * instances; break; case PrimitiveType.TriangleList: case PrimitiveType.TriangleFan: case PrimitiveType.TriangleStrip: state.Application.currentFrame.TrianglesDrawn += primitives * instances; break; } #endif #if !XBOX360 if (frequency != null && frequency.frequency.Length >= this.buffers.Length) { device.Vertices[0].SetFrequency(1); } #endif for (int i = 0; i < buffers.Length; i++) { if (i > 0) { state.SetStream(i, null, 0, 0); } } }
void LoadGeometry(GraphicsDevice graphicsDevice, Tile tile, out int primitiveCount, out IndexBuffer indexBuffer, out VertexBuffer vertexBuffer) { primitiveCount = 0; var waterLevels = new ORTSMath.Matrix2x2(tile.WaterNW, tile.WaterNE, tile.WaterSW, tile.WaterSE); var indexData = new List <short>(16 * 16 * 2 * 3); for (var z = 0; z < tile.PatchCount; ++z) { for (var x = 0; x < tile.PatchCount; ++x) { var patch = tile.GetPatch(x, z); if (!patch.WaterEnabled) { continue; } var nw = (short)(z * 17 + x); // Vertex index in the north west corner var ne = (short)(nw + 1); var sw = (short)(nw + 17); var se = (short)(sw + 1); primitiveCount += 2; if ((z & 1) == (x & 1)) // Triangles alternate { indexData.Add(nw); indexData.Add(se); indexData.Add(sw); indexData.Add(nw); indexData.Add(ne); indexData.Add(se); } else { indexData.Add(ne); indexData.Add(se); indexData.Add(sw); indexData.Add(nw); indexData.Add(ne); indexData.Add(sw); } } } indexBuffer = new IndexBuffer(graphicsDevice, typeof(short), indexData.Count, BufferUsage.WriteOnly); indexBuffer.SetData(indexData.ToArray()); var vertexData = new List <VertexPositionNormalTexture>(17 * 17); for (var z = 0; z < 17; ++z) { for (var x = 0; x < 17; ++x) { var U = (float)x * 4; var V = (float)z * 4; var a = (float)x / 16; var b = (float)z / 16; var e = (a - 0.5f) * 2048 * Size; var n = (b - 0.5f) * 2048 * Size; var y = ORTSMath.Interpolate2D(a, b, waterLevels); vertexData.Add(new VertexPositionNormalTexture(new Vector3(e, y, n), Vector3.UnitY, new Vector2(U, V))); } } vertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionNormalTexture), vertexData.Count, BufferUsage.WriteOnly); vertexBuffer.SetData(vertexData.ToArray()); }
public void OnResetDevice(object sender, EventArgs e) { Device device = (Device)sender; device.RenderState.ZBufferEnable = true; //允许使用深度缓冲 device.RenderState.Ambient = System.Drawing.Color.White; //设定环境光为白色 device.Lights[0].Type = LightType.Directional; //设置灯光类型 device.Lights[0].Diffuse = Color.White; //设置灯光颜色 device.Lights[0].Direction = new Vector3(0, -1, 0); //设置灯光位置 device.Lights[0].Update(); //更新灯光设置,创建第一盏灯光 device.Lights[0].Enabled = true; //使设置有效 string bitmapPath = @"F:\\workdir\\VC# Based DirectX\\RoadHeight.BMP"; Bitmap bitmap = new Bitmap(bitmapPath); xCount = (bitmap.Width - 1) / 2; yCount = xCount; cellWidth = bitmap.Width / xCount; cellHeight = bitmap.Height / yCount; vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionTextured), (xCount + 1) * (yCount + 1), device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vertices = new CustomVertex.PositionTextured[(xCount + 1) * (yCount + 1)];//定义顶点 for (int i = 0; i < yCount + 1; i++) { for (int j = 0; j < xCount + 1; j++) { Color color = bitmap.GetPixel((int)(j * cellWidth), (int)(i * cellHeight)); float height = float.Parse(color.R.ToString()) + float.Parse(color.G.ToString()) + float.Parse(color.B.ToString()); height /= 10; vertices[j + i * (xCount + 1)].Position = new Vector3(j * cellWidth, height, i * cellHeight); vertices[j + i * (xCount + 1)].Tu = (float)j / (xCount + 1); vertices[j + i * (xCount + 1)].Tv = (float)i / (yCount + 1); } } vertexBuffer.SetData(vertices, 0, LockFlags.None); CamTarget = new Vector3(bitmap.Width / 2, 0f, bitmap.Height / 2);//设置摄像机目标位置 indexBuffer = new IndexBuffer(typeof(int), 6 * xCount * yCount, device, Usage.WriteOnly, Pool.Default); indices = new int[6 * xCount * yCount]; for (int i = 0; i < yCount; i++) { for (int j = 0; j < xCount; j++) { indices[6 * (j + i * xCount)] = j + i * (xCount + 1); indices[6 * (j + i * xCount) + 1] = j + (i + 1) * (xCount + 1); indices[6 * (j + i * xCount) + 2] = j + i * (xCount + 1) + 1; indices[6 * (j + i * xCount) + 3] = j + i * (xCount + 1) + 1; indices[6 * (j + i * xCount) + 4] = j + (i + 1) * (xCount + 1); indices[6 * (j + i * xCount) + 5] = j + (i + 1) * (xCount + 1) + 1; } } indexBuffer.SetData(indices, 0, LockFlags.None); /*******第1个四周边界********/ float minY = GetMinHeight(bitmapPath) - 5.0f; borderFrontVertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 2 * (xCount + 1),//四周的一个面封闭总共所需要的顶点的数目 device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); borderFrontVertices = new CustomVertex.PositionColored[2 * (xCount + 1)];//定义顶点 int k; for (k = 0; k < xCount + 1; k++)//X轴上的点的定义 { borderFrontVertices[k].Position = new Vector3(k * cellWidth, minY, 0.0f); borderFrontVertices[k].Color = System.Drawing.Color.Red.ToArgb(); } for (; k < 2 * (xCount + 1); k++)//高程图上的边界点的定义 { Color color = bitmap.GetPixel((int)((k - xCount - 1) * cellWidth), 0); float height = float.Parse(color.R.ToString()) + float.Parse(color.G.ToString()) + float.Parse(color.B.ToString()); height /= 10; borderFrontVertices[k].Position = new Vector3((k - xCount - 1) * cellWidth, height, 0);//i * cellHeight=0 borderFrontVertices[k].Color = System.Drawing.Color.Aqua.ToArgb(); } borderFrontVertexBuffer.SetData(borderFrontVertices, 0, LockFlags.None); borderFrontIndexBuffer = new IndexBuffer(typeof(int), 6 * xCount * 1, device, Usage.WriteOnly, Pool.Default); borderFrontIndices = new int[6 * xCount * 1];//初始化索引顶点 for (int j = 0; j < xCount; j++) { borderFrontIndices[6 * (j)] = j; borderFrontIndices[6 * (j) + 1] = j + (xCount + 1); borderFrontIndices[6 * (j) + 2] = j + 1; borderFrontIndices[6 * (j) + 3] = j + 1; borderFrontIndices[6 * (j) + 4] = j + (xCount + 1); borderFrontIndices[6 * (j) + 5] = j + (xCount + 1) + 1; } borderFrontIndexBuffer.SetData(borderFrontIndices, 0, LockFlags.None); /**第2个四周边界**/ borderBackVertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 2 * (xCount + 1),//四周的一个面封闭总共所需要的顶点的数目 device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); borderBackVertices = new CustomVertex.PositionColored[2 * (xCount + 1)]; //定义顶点 for (k = 0; k < xCount + 1; k++) //X轴平行方向上的点的定义 { borderBackVertices[k].Position = new Vector3(k * cellWidth, minY, yCount * cellHeight); borderBackVertices[k].Color = System.Drawing.Color.Aqua.ToArgb(); } for (; k < 2 * (xCount + 1); k++) //高程图上的边界点的定义 { Color color = bitmap.GetPixel((int)((k - xCount - 1) * cellWidth), (int)(yCount * cellHeight)); //不能直接写死 float height = float.Parse(color.R.ToString()) + float.Parse(color.G.ToString()) + float.Parse(color.B.ToString()); height /= 10; borderBackVertices[k].Position = new Vector3((k - xCount - 1) * cellWidth, height, yCount * cellHeight); borderBackVertices[k].Color = System.Drawing.Color.Aqua.ToArgb(); } borderBackVertexBuffer.SetData(borderBackVertices, 0, LockFlags.None); borderBackIndexBuffer = new IndexBuffer(typeof(int), 6 * xCount * 1, device, Usage.WriteOnly, Pool.Default); borderBackIndices = new int[6 * xCount * 1];//初始化索引顶点 for (int j = 0; j < xCount; j++) { borderBackIndices[6 * (j)] = j; borderBackIndices[6 * (j) + 1] = j + (xCount + 1); borderBackIndices[6 * (j) + 2] = j + 1; borderBackIndices[6 * (j) + 3] = j + 1; borderBackIndices[6 * (j) + 4] = j + (xCount + 1); borderBackIndices[6 * (j) + 5] = j + (xCount + 1) + 1; } borderBackIndexBuffer.SetData(borderBackIndices, 0, LockFlags.None); int diff = yCount - xCount; /**第3个四周边界**/ borderLeftVertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 2 * (yCount + 1),//四周的一个面封闭总共所需要的顶点的数目 device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); borderLeftVertices = new CustomVertex.PositionColored[2 * (yCount + 1)]; //定义顶点 for (k = 0; k < yCount + 1; k++) //Z轴平行方向上的点的定义 { borderLeftVertices[k].Position = new Vector3(0, minY, k * cellHeight); borderLeftVertices[k].Color = System.Drawing.Color.Aqua.ToArgb(); } for (; k < 2 * (yCount + 1); k++) //高程图上的边界点的定义 { Color color = bitmap.GetPixel(0, (int)((k - yCount - 1) * cellHeight)); //边界点不能直接传进去写死,容易产生溢出的异常 float height = float.Parse(color.R.ToString()) + float.Parse(color.G.ToString()) + float.Parse(color.B.ToString()); height /= 10; borderLeftVertices[k].Position = new Vector3(0, height, (k - yCount - 1) * cellHeight); borderLeftVertices[k].Color = System.Drawing.Color.Aqua.ToArgb(); } borderLeftVertexBuffer.SetData(borderLeftVertices, 0, LockFlags.None); borderLeftIndexBuffer = new IndexBuffer(typeof(int), 6 * yCount * 1, device, Usage.WriteOnly, Pool.Default); borderLeftIndices = new int[6 * yCount * 1];//初始化索引顶点 for (int j = 0; j < yCount; j++) { borderLeftIndices[6 * (j)] = j; borderLeftIndices[6 * (j) + 1] = j + (yCount + 1); borderLeftIndices[6 * (j) + 2] = j + 1; borderLeftIndices[6 * (j) + 3] = j + 1; borderLeftIndices[6 * (j) + 4] = j + (yCount + 1); borderLeftIndices[6 * (j) + 5] = j + (yCount + 1) + 1; } borderLeftIndexBuffer.SetData(borderLeftIndices, 0, LockFlags.None); //MessageBox.Show(borderLeftIndices[0]+","+borderLeftIndices[1]+","+borderLeftIndices[2]); /**第4个四周边界**/ borderRightVertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 2 * (yCount + 1),//四周的一个面封闭总共所需要的顶点的数目 device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); borderRightVertices = new CustomVertex.PositionColored[2 * (yCount + 1)]; //定义顶点 for (k = 0; k < yCount + 1; k++) //Z轴平行方向上的点的定义 { borderRightVertices[k].Position = new Vector3(xCount * cellWidth, minY, k * cellHeight); borderRightVertices[k].Color = System.Drawing.Color.Aqua.ToArgb(); } for (; k < 2 * (yCount + 1); k++) //高程图上的边界点的定义 { Color color = bitmap.GetPixel((int)(xCount * cellWidth), (int)((k - yCount - 1) * cellHeight)); //边界点不能直接传进去写死,容易产生溢出和精度损失 float height = float.Parse(color.R.ToString()) + float.Parse(color.G.ToString()) + float.Parse(color.B.ToString()); height /= 10; borderRightVertices[k].Position = new Vector3(xCount * cellWidth, height, (k - yCount - 1) * cellHeight); borderRightVertices[k].Color = System.Drawing.Color.Aqua.ToArgb(); } borderRightVertexBuffer.SetData(borderRightVertices, 0, LockFlags.None); borderRightIndexBuffer = new IndexBuffer(typeof(int), 6 * yCount * 1, device, Usage.WriteOnly, Pool.Default); borderRightIndices = new int[6 * yCount * 1];//初始化索引顶点 for (int j = 0; j < yCount; j++) { borderRightIndices[6 * (j)] = j; borderRightIndices[6 * (j) + 1] = j + (yCount + 1); borderRightIndices[6 * (j) + 2] = j + 1; borderRightIndices[6 * (j) + 3] = j + 1; borderRightIndices[6 * (j) + 4] = j + (yCount + 1); borderRightIndices[6 * (j) + 5] = j + (yCount + 1) + 1; } borderRightIndexBuffer.SetData(borderRightIndices, 0, LockFlags.None); device.SamplerState[0].MagFilter = TextureFilter.Linear;//使用纹理滤波器进行线性滤波 }
public void DrawGeometry(Microsoft.Xna.Framework.Graphics.GraphicsDevice device, Effect effect) { //Effect.CurrentTechnique = Effect.Techniques[0]; if (SkelBones == null) { ReloadSkeleton(); } effect.Parameters["SkelBindings"].SetValue(SkelBones); lock (Bindings) { foreach (var pass in effect.CurrentTechnique.Passes) { foreach (var binding in Bindings) { if (binding.Texture != null) { var tex = binding.Texture.Get(device); effect.Parameters["MeshTex"].SetValue(tex); } else { effect.Parameters["MeshTex"].SetValue((Texture2D)null); } pass.Apply(); binding.Mesh.Draw(device); } } } //skip drawing shadows if we're drawing id if (LightPositions == null || effect.CurrentTechnique == effect.Techniques[1]) { return; } if (ShadBuf == null) { var shadVerts = new ShadowVertex[] { new ShadowVertex(new Vector3(-1, 0, -1), 25), new ShadowVertex(new Vector3(-1, 0, 1), 25), new ShadowVertex(new Vector3(1, 0, 1), 25), new ShadowVertex(new Vector3(1, 0, -1), 25), new ShadowVertex(new Vector3(-1, 0, -1), 19), new ShadowVertex(new Vector3(-1, 0, 1), 19), new ShadowVertex(new Vector3(1, 0, 1), 19), new ShadowVertex(new Vector3(1, 0, -1), 19) }; for (int i = 0; i < shadVerts.Length; i++) { shadVerts[i].Position *= 1f; } int[] shadInd = new int[] { 2, 1, 0, 2, 0, 3, 6, 5, 4, 6, 4, 7 }; ShadBuf = new VertexBuffer(device, typeof(ShadowVertex), shadVerts.Length, BufferUsage.None); ShadBuf.SetData(shadVerts); ShadIBuf = new IndexBuffer(device, IndexElementSize.ThirtyTwoBits, shadInd.Length, BufferUsage.None); ShadIBuf.SetData(shadInd); } foreach (var light in LightPositions) { //effect.Parameters["FloorHeight"].SetValue((float)(Math.Floor(Position.Y/2.95)*2.95 + 0.05)); effect.Parameters["LightPosition"].SetValue(light); var oldTech = effect.CurrentTechnique; effect.CurrentTechnique = Avatar.Effect.Techniques[4]; effect.CurrentTechnique.Passes[0].Apply(); device.DepthStencilState = DepthStencilState.DepthRead; device.SetVertexBuffer(ShadBuf); device.Indices = ShadIBuf; device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4); effect.CurrentTechnique = oldTech; device.DepthStencilState = DepthStencilState.Default; } DrawHeadObject(device, effect); }
private static void ReadVertexBuffer(FSHP fshp, VertexBuffer vtx, FMDL model) { fshp.vertices.Clear(); fshp.vertexAttributes.Clear(); //Create a buffer instance which stores all the buffer data VertexBufferHelper helper = new VertexBufferHelper(vtx, Syroot.BinaryData.ByteOrder.BigEndian); //Set each array first from the lib if exist. Then add the data all in one loop Syroot.Maths.Vector4F[] vec4Positions = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4Normals = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4uv0 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4uv1 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4uv2 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4c0 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4t0 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4b0 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4w0 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4i0 = new Syroot.Maths.Vector4F[0]; //For shape morphing Syroot.Maths.Vector4F[] vec4Positions1 = new Syroot.Maths.Vector4F[0]; Syroot.Maths.Vector4F[] vec4Positions2 = new Syroot.Maths.Vector4F[0]; foreach (VertexAttrib att in vtx.Attributes.Values) { FSHP.VertexAttribute attr = new FSHP.VertexAttribute(); attr.Name = att.Name; attr.Format = attr.GetTypeWiiU(att.Format); if (att.Name == "_p0") { vec4Positions = AttributeData(att, helper, "_p0"); } if (att.Name == "_n0") { vec4Normals = AttributeData(att, helper, "_n0"); } if (att.Name == "_u0") { vec4uv0 = AttributeData(att, helper, "_u0"); } if (att.Name == "_u1") { vec4uv1 = AttributeData(att, helper, "_u1"); } if (att.Name == "_u2") { vec4uv2 = AttributeData(att, helper, "_u2"); } if (att.Name == "_c0") { vec4c0 = AttributeData(att, helper, "_c0"); } if (att.Name == "_t0") { vec4t0 = AttributeData(att, helper, "_t0"); } if (att.Name == "_b0") { vec4b0 = AttributeData(att, helper, "_b0"); } if (att.Name == "_w0") { vec4w0 = AttributeData(att, helper, "_w0"); } if (att.Name == "_i0") { vec4i0 = AttributeData(att, helper, "_i0"); } if (att.Name == "_p1") { vec4Positions1 = AttributeData(att, helper, "_p1"); } if (att.Name == "_p2") { vec4Positions2 = AttributeData(att, helper, "_p2"); } fshp.vertexAttributes.Add(attr); } for (int i = 0; i < vec4Positions.Length; i++) { Vertex v = new Vertex(); if (vec4Positions.Length > 0) { v.pos = new Vector3(vec4Positions[i].X, vec4Positions[i].Y, vec4Positions[i].Z); } if (vec4Positions1.Length > 0) { v.pos1 = new Vector3(vec4Positions1[i].X, vec4Positions1[i].Y, vec4Positions1[i].Z); } if (vec4Positions2.Length > 0) { v.pos2 = new Vector3(vec4Positions2[i].X, vec4Positions2[i].Y, vec4Positions2[i].Z); } if (vec4Normals.Length > 0) { v.nrm = new Vector3(vec4Normals[i].X, vec4Normals[i].Y, vec4Normals[i].Z); } if (vec4uv0.Length > 0) { v.uv0 = new Vector2(vec4uv0[i].X, vec4uv0[i].Y); } if (vec4uv1.Length > 0) { v.uv1 = new Vector2(vec4uv1[i].X, vec4uv1[i].Y); } if (vec4uv2.Length > 0) { v.uv2 = new Vector2(vec4uv2[i].X, vec4uv2[i].Y); } if (vec4w0.Length > 0) { v.boneWeights.Add(vec4w0[i].X); v.boneWeights.Add(vec4w0[i].Y); v.boneWeights.Add(vec4w0[i].Z); v.boneWeights.Add(vec4w0[i].W); } if (vec4i0.Length > 0) { v.boneIds.Add((int)vec4i0[i].X); v.boneIds.Add((int)vec4i0[i].Y); v.boneIds.Add((int)vec4i0[i].Z); v.boneIds.Add((int)vec4i0[i].W); } if (vec4t0.Length > 0) { v.tan = new Vector4(vec4t0[i].X, vec4t0[i].Y, vec4t0[i].Z, vec4t0[i].W); } if (vec4b0.Length > 0) { v.bitan = new Vector4(vec4b0[i].X, vec4b0[i].Y, vec4b0[i].Z, vec4b0[i].W); } if (vec4c0.Length > 0) { v.col = new Vector4(vec4c0[i].X, vec4c0[i].Y, vec4c0[i].Z, vec4c0[i].W); } if (fshp.VertexSkinCount == 1) { Matrix4 sb = model.Skeleton.bones[model.Skeleton.Node_Array[v.boneIds[0]]].transform; v.pos = Vector3.TransformPosition(v.pos, sb); v.nrm = Vector3.TransformNormal(v.nrm, sb); } if (fshp.VertexSkinCount == 0) { Matrix4 NoBindFix = model.Skeleton.bones[fshp.boneIndx].transform; v.pos = Vector3.TransformPosition(v.pos, NoBindFix); v.nrm = Vector3.TransformNormal(v.nrm, NoBindFix); } fshp.vertices.Add(v); } }
protected override void LoadContent() { _shader = CreateShader(); _vertexBuffer = CreateVertexBuffer(); }
/// <summary> /// Convierte el Triángulo 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; //Crear Mesh con solo color Mesh d3dMesh = new Mesh(1, 3, MeshFlags.Managed, TgcSceneLoader.TgcSceneLoader.VertexColorVertexElements, d3dDevice); //Calcular normal: left-handed Vector3 normal = computeNormal(); int ci = color.ToArgb(); //Cargar VertexBuffer using (VertexBuffer vb = d3dMesh.VertexBuffer) { GraphicsStream data = vb.Lock(0, 0, LockFlags.None); TgcSceneLoader.TgcSceneLoader.VertexColorVertex v; //a v = new TgcSceneLoader.TgcSceneLoader.VertexColorVertex(); v.Position = a; v.Normal = normal; v.Color = ci; data.Write(v); //b v = new TgcSceneLoader.TgcSceneLoader.VertexColorVertex(); v.Position = b; v.Normal = normal; v.Color = ci; data.Write(v); //c v = new TgcSceneLoader.TgcSceneLoader.VertexColorVertex(); v.Position = c; v.Normal = normal; v.Color = ci; data.Write(v); vb.Unlock(); } //Cargar IndexBuffer en forma plana using (IndexBuffer ib = d3dMesh.IndexBuffer) { short[] indices = new short[3]; 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); }
// build links private void VertexDeclarationLinks() { vertices = new CustomVertex.PositionColored[5]; /* conner layout * A---B * / * C---D * */ int widthOfLink = 10; int mGripperStepPluse = (int)(cGripperStepPluse * 0.7f); vertices[0].Position = new Vector3(rails[0].start_Loc_x + mGripperStepPluse, rails[0].start_Loc_y - rails[0].width + (mGripperStepPluse * widthOfLink), 0f); // corner A vertices[1].Position = new Vector3(rails[0].start_Loc_x - mGripperStepPluse, rails[0].start_Loc_y - rails[0].width + (mGripperStepPluse * widthOfLink), 0f); // conner B vertices[2].Position = new Vector3(rails[0].start_Loc_x + mGripperStepPluse, rails[0].start_Loc_y - rails[0].width - (mGripperStepPluse * widthOfLink), 0f); // conner C vertices[3].Position = new Vector3(rails[0].start_Loc_x - mGripperStepPluse, rails[0].start_Loc_y - rails[0].width - (mGripperStepPluse * widthOfLink), 0f); // conner D //white vertices[0].Color = Color.White.ToArgb(); vertices[1].Color = Color.White.ToArgb(); vertices[2].Color = Color.White.ToArgb(); vertices[3].Color = Color.White.ToArgb(); vb_Link_White = new VertexBuffer(typeof(CustomVertex.PositionColored), 5, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vb_Link_White.SetData(vertices, 0, LockFlags.None); //blue vertices[0].Color = Color.Blue.ToArgb(); vertices[1].Color = Color.Blue.ToArgb(); vertices[2].Color = Color.Blue.ToArgb(); vertices[3].Color = Color.Blue.ToArgb(); vb_Link_Blue = new VertexBuffer(typeof(CustomVertex.PositionColored), 5, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vb_Link_Blue.SetData(vertices, 0, LockFlags.None); //red vertices[0].Color = Color.Red.ToArgb(); vertices[1].Color = Color.Red.ToArgb(); vertices[2].Color = Color.Red.ToArgb(); vertices[3].Color = Color.Red.ToArgb(); vb_Link_Red = new VertexBuffer(typeof(CustomVertex.PositionColored), 5, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vb_Link_Red.SetData(vertices, 0, LockFlags.None); //Green vertices[0].Color = Color.Green.ToArgb(); vertices[1].Color = Color.Green.ToArgb(); vertices[2].Color = Color.Green.ToArgb(); vertices[3].Color = Color.Green.ToArgb(); vb_Link_Green = new VertexBuffer(typeof(CustomVertex.PositionColored), 5, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vb_Link_Green.SetData(vertices, 0, LockFlags.None); //Orange vertices[0].Color = Color.Orange.ToArgb(); vertices[1].Color = Color.Orange.ToArgb(); vertices[2].Color = Color.Orange.ToArgb(); vertices[3].Color = Color.Orange.ToArgb(); vb_Link_Orange = new VertexBuffer(typeof(CustomVertex.PositionColored), 5, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vb_Link_Orange.SetData(vertices, 0, LockFlags.None); }
public static void FlipFontAtlas(RenderContext renderContext, Texture2D texture) { var previousFrameBuffer = renderContext.FrameBuffer; var previousScissorTest = renderContext.ScissorTest; var previousDepthTest = renderContext.DepthTest; var previousViewport = renderContext.ViewportRectangle; var previousCullBackfaces = renderContext.CullBackfaces; var previousBlend = renderContext.Blend; renderContext.GetBlendFunc(out var previousSFactor, out var previousDFactor); renderContext.ScissorTest = false; renderContext.DepthTest = false; renderContext.ViewportRectangle = new Rectangle(0, 0, texture._width, texture._height); renderContext.CullBackfaces = false; renderContext.SetBlendFunc(BlendingFactor.One, BlendingFactor.Zero); var shaderProgram = CreateAtlasFlippingProgram(renderContext); var tempFrameBuffer = new FrameBuffer(renderContext, texture._width, texture._height, FrameBufferFlags.Color); var atlasFrameBuffer = new FrameBuffer(renderContext, texture); VertexPosition2Texture[] vertices = { new VertexPosition2Texture(new Vector2(0, 0), new Vector2(0, 1)), new VertexPosition2Texture(new Vector2(texture._width, 0), new Vector2(1, 1)), new VertexPosition2Texture(new Vector2(texture._width, texture._height), new Vector2(1, 0)), new VertexPosition2Texture(new Vector2(0, texture._height), new Vector2(0, 0)), }; uint[] indices = { 2, 1, 0, 2, 0, 3, }; var vertexBuffer = VertexBuffer.Create(renderContext, vertices, BufferUsageHint.StaticDraw, true); var indexBuffer = IndexBuffer.Create(renderContext, indices, BufferUsageHint.StaticDraw, true); // Draw atlas texture to temporary frame buffer. renderContext.BindFrameBuffer(tempFrameBuffer); renderContext.Clear(Color.Transparent); renderContext.BindTexture2D(0, texture); shaderProgram.SetUniform("projection", Matrix4x4.CreateOrthographicOffCenter(0f, texture._width, texture._height, 0f, -1f, 1f)); renderContext.Render(PrimitiveType.Triangles, vertexBuffer, indexBuffer, shaderProgram); // Draw temporary render target to atlas texture. renderContext.BindFrameBuffer(atlasFrameBuffer); renderContext.Clear(Color.Transparent); renderContext.BindTexture2D(0, tempFrameBuffer.ColorTexture); shaderProgram.SetUniform("projection", Matrix4x4.CreateOrthographicOffCenter(0f, texture._width, 0f, texture._height, -1f, 1f)); renderContext.Render(PrimitiveType.Triangles, vertexBuffer, indexBuffer, shaderProgram); renderContext.ViewportRectangle = previousViewport; renderContext.DepthTest = previousDepthTest; renderContext.ScissorTest = previousScissorTest; renderContext.CullBackfaces = previousCullBackfaces; renderContext.Blend = previousBlend; renderContext.SetBlendFunc(previousSFactor, previousDFactor); renderContext.BindFrameBuffer(previousFrameBuffer); vertexBuffer.Dispose(); indexBuffer.Dispose(); tempFrameBuffer.Dispose(); atlasFrameBuffer.Dispose(); shaderProgram.Dispose(); }
internal void SetBaseTexture(int[,] optimizedArray, Bitmap hiResBitmap) { lock (this) { if (optimizedTexture != null) { optimizedTexture.Dispose(); optimizedTexture = null; } if (hiResTexture != null) { hiResTexture.Dispose(); hiResTexture = null; } if (hiResTexture == null) { // The obvious solution would be: // hiResTexture = new Texture(myDevice, hiResBitmap, Usage.AutoGenerateMipMap, Pool.Managed); // But that doesn't work for reading. int wHi = hiResBitmap.Width; int hHi = hiResBitmap.Height; int maxMipLevel = (int)(1.5 + Math.Log(Math.Min(wHi, hHi), 2.0)); hiResTexture = new Texture(myDevice, wHi, hHi, maxMipLevel, Usage.None, Format.L8, Pool.Managed); byte[,] hiResTextureArray = (byte[, ])hiResTexture.LockRectangle(typeof(byte), 0, LockFlags.None, new int[] { hHi, wHi }); for (int j = 0; j < hHi; j++) { for (int i = 0; i < wHi; i++) { hiResTextureArray[j, i] = hiResBitmap.GetPixel(i, j).R; } } hiResTexture.UnlockRectangle(0); TextureLoader.FilterTexture(hiResTexture, 0, Filter.Box); } int w = optimizedArray.GetLength(1); int h = optimizedArray.GetLength(0); int downsampling = hiResTexture.GetLevelDescription(0).Width / w; int levelOffset = (int)(0.5 + Math.Log(downsampling, 2.0)); optimizedTexture = new Texture(myDevice, w, h, hiResTexture.LevelCount - levelOffset, 0, Format.L8, Pool.Managed); // skip the first level; that's filled dynamically for (int level = 1; level < hiResTexture.LevelCount - levelOffset; level++) { int scale = (int)(0.5 + Math.Pow(2.0, level)); byte[,] originalTextureArray = (byte[, ])hiResTexture.LockRectangle(typeof(byte), level + levelOffset, LockFlags.ReadOnly, new int[] { h / scale, w / scale }); byte[,] optimizedTextureArray = (byte[, ])optimizedTexture.LockRectangle(typeof(byte), level, LockFlags.None, new int[] { h / scale, w / scale }); int wLevel = w / scale; int hLevel = h / scale; for (int j = 0; j < hLevel; j++) { for (int i = 0; i < wLevel; i++) { int x = optimizedTextureArray[j, i]; optimizedTextureArray[j, i] = (byte)originalTextureArray[j, i]; } } optimizedTexture.UnlockRectangle(level); hiResTexture.UnlockRectangle(level + levelOffset); } if (myVertexBuffer != null) { myVertexBuffer.Dispose(); } myVertexBuffer = new VertexBuffer(typeof(DualTextureVertex), 4, myDevice, Usage.WriteOnly, 0, Pool.Managed); DualTextureVertex[] myVertexData = new DualTextureVertex[4]; float aspectRatio = h / (float)w; myVertexData[0] = new DualTextureVertex(-1.0f, aspectRatio, 0.0f, 0.0f, 0.0f, 0, 0); myVertexData[1] = new DualTextureVertex(-1.0f, -aspectRatio, 0.0f, 0.0f, 1.0f, 0, h); myVertexData[2] = new DualTextureVertex(1.0f, aspectRatio, 0.0f, 1.0f, 0.0f, w, 0); myVertexData[3] = new DualTextureVertex(1.0f, -aspectRatio, 0.0f, 1.0f, 1.0f, w, h); myVertexBuffer.SetData(myVertexData, 0, LockFlags.None); } }
public static void DrawBoundingBox(BoundingBox boundingBox, Matrix view, Matrix projection) { if (_boxVertexBuffer == null) //was never setup { float alpha = 0.5f; if (_boxVertexDeclaration == null) { _boxVertexDeclaration = new VertexDeclaration(ResourceMgr.Instance.Game.GraphicsDevice, VertexPositionColor.VertexElements); } _boxVertexBuffer = new VertexBuffer(ResourceMgr.Instance.Game.GraphicsDevice, VertexPositionColor.SizeInBytes * 24, BufferUsage.WriteOnly); if (_boxIndexBuffer == null) { _boxIndexBuffer = new IndexBuffer(ResourceMgr.Instance.Game.GraphicsDevice, 2 /*bytes*/ * 6 * 6, BufferUsage.WriteOnly, IndexElementSize.SixteenBits); short[] indices = new short[36]; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 1; indices[4] = 3; indices[5] = 2; indices[6] = 4; indices[7] = 5; indices[8] = 6; indices[9] = 6; indices[10] = 5; indices[11] = 7; indices[12] = 8; indices[13] = 9; indices[14] = 10; indices[15] = 8; indices[16] = 11; indices[17] = 9; indices[18] = 12; indices[19] = 13; indices[20] = 14; indices[21] = 12; indices[22] = 14; indices[23] = 15; indices[24] = 16; indices[25] = 17; indices[26] = 18; indices[27] = 19; indices[28] = 17; indices[29] = 16; indices[30] = 20; indices[31] = 21; indices[32] = 22; indices[33] = 23; indices[34] = 20; indices[35] = 22; _boxIndexBuffer.SetData <short>(indices); } _boxEffect = new BasicEffect(ResourceMgr.Instance.Game.GraphicsDevice, null); _boxEffect.VertexColorEnabled = true; _boxEffect.Alpha = alpha; VertexPositionColor[] vertices = new VertexPositionColor[24]; Vector3 topLeftFront = new Vector3(-0.5f, 0.5f, 0.5f); Vector3 bottomLeftFront = new Vector3(-0.5f, -0.5f, 0.5f); Vector3 topRightFront = new Vector3(0.5f, 0.5f, 0.5f); Vector3 bottomRightFront = new Vector3(0.5f, -0.5f, 0.5f); Vector3 topLeftBack = new Vector3(-0.5f, 0.5f, -0.5f); Vector3 topRightBack = new Vector3(0.5f, 0.5f, -0.5f); Vector3 bottomLeftBack = new Vector3(-0.5f, -0.5f, -0.5f); Vector3 bottomRightBack = new Vector3(0.5f, -0.5f, -0.5f); //front vertices[0] = new VertexPositionColor(topLeftFront, Color.Red); vertices[1] = new VertexPositionColor(bottomLeftFront, Color.Red); vertices[2] = new VertexPositionColor(topRightFront, Color.Red); vertices[3] = new VertexPositionColor(bottomRightFront, Color.Red); //back vertices[4] = new VertexPositionColor(topLeftBack, Color.Orange); vertices[5] = new VertexPositionColor(topRightBack, Color.Orange); vertices[6] = new VertexPositionColor(bottomLeftBack, Color.Orange); vertices[7] = new VertexPositionColor(bottomRightBack, Color.Orange); //top vertices[8] = new VertexPositionColor(topLeftFront, Color.Yellow); vertices[9] = new VertexPositionColor(topRightBack, Color.Yellow); vertices[10] = new VertexPositionColor(topLeftBack, Color.Yellow); vertices[11] = new VertexPositionColor(topRightFront, Color.Yellow); //bottom vertices[12] = new VertexPositionColor(bottomLeftFront, Color.Purple); vertices[13] = new VertexPositionColor(bottomLeftBack, Color.Purple); vertices[14] = new VertexPositionColor(bottomRightBack, Color.Purple); vertices[15] = new VertexPositionColor(bottomRightFront, Color.Purple); //left vertices[16] = new VertexPositionColor(topLeftFront, Color.Blue); vertices[17] = new VertexPositionColor(bottomLeftBack, Color.Blue); vertices[18] = new VertexPositionColor(bottomLeftFront, Color.Blue); vertices[19] = new VertexPositionColor(topLeftBack, Color.Blue); //right vertices[20] = new VertexPositionColor(topRightFront, Color.Green); vertices[21] = new VertexPositionColor(bottomRightFront, Color.Green); vertices[22] = new VertexPositionColor(bottomRightBack, Color.Green); vertices[23] = new VertexPositionColor(topRightBack, Color.Green); _boxVertexBuffer.SetData <VertexPositionColor>(vertices); } Matrix scale = Matrix.CreateScale(boundingBox.Max.X - boundingBox.Min.X, boundingBox.Max.Y - boundingBox.Min.Y, boundingBox.Max.Z - boundingBox.Min.Z); Matrix translation = Matrix.CreateTranslation(BoxCenter(boundingBox)); Matrix adjustment = scale * translation; ResourceMgr.Instance.Game.GraphicsDevice.RenderState.CullMode = CullMode.None; ResourceMgr.Instance.Game.GraphicsDevice.Vertices[0].SetSource(_boxVertexBuffer, 0, VertexPositionColor.SizeInBytes); ResourceMgr.Instance.Game.GraphicsDevice.Indices = _boxIndexBuffer; VertexDeclaration old = ResourceMgr.Instance.Game.GraphicsDevice.VertexDeclaration; ResourceMgr.Instance.Game.GraphicsDevice.VertexDeclaration = _boxVertexDeclaration; ResourceMgr.Instance.Game.GraphicsDevice.RenderState.AlphaBlendEnable = true; ResourceMgr.Instance.Game.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha; ResourceMgr.Instance.Game.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha; _boxEffect.Begin(); _boxEffect.View = view; _boxEffect.Projection = projection; _boxEffect.World = adjustment; foreach (EffectPass pass in _boxEffect.CurrentTechnique.Passes) { pass.Begin(); ResourceMgr.Instance.Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 24, 0, 12); pass.End(); } _boxEffect.End(); ResourceMgr.Instance.Game.GraphicsDevice.VertexDeclaration = old; ResourceMgr.Instance.Game.GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace; ResourceMgr.Instance.Game.GraphicsDevice.RenderState.AlphaBlendEnable = false; }
public override void Init() { MyShaderDir = ShadersDir + "WorkshopShaders\\"; //Crear loader var loader = new TgcSceneLoader(); //Cargar mesh scene = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Teapot\\Teapot-TgcScene.xml"); mesh = scene.Meshes[0]; mesh.Scale = new Vector3(1f, 1f, 1f); mesh.Position = new Vector3(-100f, -5f, 0f); // Arreglo las normales var adj = new int[mesh.D3dMesh.NumberFaces * 3]; mesh.D3dMesh.GenerateAdjacency(0, adj); mesh.D3dMesh.ComputeNormals(adj); //Cargar Shader personalizado effect = TgcShaders.loadEffect(MyShaderDir + "ToonShading.fx"); // le asigno el efecto a la malla mesh.Effect = effect; mesh.Technique = "DefaultTechnique"; // Creo las instancias de malla instances = new List <TgcMesh>(); for (var i = -5; i < 5; i++) { for (var j = -5; j < 5; j++) { var instance = mesh.createMeshInstance(mesh.Name + i); instance.move(i * 50, (i + j) * 5, j * 50); instances.Add(instance); } } Modifiers.addVertex3f("LightPosition", new Vector3(-100, -100, -100), new Vector3(100, 100, 100), new Vector3(0, 40, 0)); Modifiers.addFloat("Ambient", 0, 1, 0.5f); Modifiers.addFloat("Diffuse", 0, 1, 0.6f); Modifiers.addFloat("Specular", 0, 1, 0.5f); Modifiers.addFloat("SpecularPower", 1, 100, 16); Camara = new TgcRotationalCamera(new Vector3(20, 20, 0), 300, TgcRotationalCamera.DEFAULT_ZOOM_FACTOR, 1.5f); // Creo un depthbuffer sin multisampling, para que sea compatible con el render to texture // Nota: // El render to Texture no es compatible con el multisampling en dx9 // Por otra parte la mayor parte de las placas de ultima generacion no soportan // mutisampling para texturas de punto flotante con lo cual // hay que suponer con generalidad que no se puede usar multisampling y render to texture // Para resolverlo hay que crear un depth buffer que no tenga multisampling, // (de lo contrario falla el zbuffer y se producen artifacts tipicos de que no tiene zbuffer) // Si uno quisiera usar el multisampling, la tecnica habitual es usar un RenderTarget // en lugar de una textura. // Por ejemplo en c++: // // Render Target formato color buffer con multisampling // // g_pd3dDevice->CreateRenderTarget(Ancho,Alto, // D3DFMT_A8R8G8B8, D3DMULTISAMPLE_2_SAMPLES, 0, // FALSE, &g_pRenderTarget, NULL); // // Luego, ese RenderTarget NO ES una textura, y nosotros necesitamos acceder a esos // pixeles, ahi lo que se hace es COPIAR del rendertartet a una textura, // para poder trabajar con esos datos en el contexto del Pixel shader: // // Eso se hace con la funcion StretchRect: // copia de rendertarget ---> sceneSurface (que es la superficie asociada a una textura) // g_pd3dDevice->StretchRect(g_pRenderTarget, NULL, g_pSceneSurface, NULL, D3DTEXF_NONE); // // Esta tecnica se llama downsampling // Y tiene el costo adicional de la transferencia de memoria entre el rendertarget y la // textura, pero que no traspasa los limites de la GPU. (es decir es muy performante) // no es lo mismo que lockear una textura para acceder desde la CPU, que tiene el problema // de transferencia via AGP. g_pDepthStencil = D3DDevice.Instance.Device.CreateDepthStencilSurface( D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); // inicializo el render target g_pRenderTarget = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth , D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); effect.SetValue("g_RenderTarget", g_pRenderTarget); // inicializo el mapa de normales g_pNormals = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth , D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default); effect.SetValue("g_Normals", g_pNormals); // Resolucion de pantalla effect.SetValue("screen_dx", D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth); effect.SetValue("screen_dy", D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight); //Se crean 2 triangulos con las dimensiones de la pantalla con sus posiciones ya transformadas // x = -1 es el extremo izquiedo de la pantalla, x=1 es el extremo derecho // Lo mismo para la Y con arriba y abajo // la Z en 1 simpre CustomVertex.PositionTextured[] vertices = { new CustomVertex.PositionTextured(-1, 1, 1, 0, 0), new CustomVertex.PositionTextured(1, 1, 1, 1, 0), new CustomVertex.PositionTextured(-1, -1, 1, 0, 1), new CustomVertex.PositionTextured(1, -1, 1, 1, 1) }; //vertex buffer de los triangulos g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, D3DDevice.Instance.Device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); g_pVBV3D.SetData(vertices, 0, LockFlags.None); efecto_blur = false; }
//build rails private void VertexDeclarationRails() { int i = 0; for (i = 0; i < rails.Length; i++) { // set start point for rail zero if (i == 0) { rails[i].start_Loc_x = startX; rails[i].start_Loc_y = startY; } else { //goto the end of the last rail // get last riad direct so we know how to find its tail. if (rails[i - 1].directionOfTravel == (int)ClassDef.clsRail.direction.right) { rails[i].start_Loc_x = rails[i - 1].start_Loc_x - rails[i - 1].lenght; // +(rails[i - 1].width * 1); rails[i].start_Loc_y = rails[i - 1].start_Loc_y; // - (rails[i - 1].width * 1); } if (rails[i - 1].directionOfTravel == (int)ClassDef.clsRail.direction.left) { rails[i].start_Loc_x = rails[i - 1].start_Loc_x + rails[i - 1].lenght; // + (rails[i - 1].width * 1); rails[i].start_Loc_y = rails[i - 1].start_Loc_y; // + (rails[i - 1].width * 1); } if (rails[i - 1].directionOfTravel == (int)ClassDef.clsRail.direction.up) { rails[i].start_Loc_x = rails[i - 1].start_Loc_x; // - (rails[i - 1].width * 1); rails[i].start_Loc_y = rails[i - 1].start_Loc_y + rails[i - 1].lenght; // - (rails[i - 1].width * 1); } if (rails[i - 1].directionOfTravel == (int)ClassDef.clsRail.direction.down) { rails[i].start_Loc_x = rails[i - 1].start_Loc_x; // - (rails[i - 1].width * 1); rails[i].start_Loc_y = rails[i - 1].start_Loc_y - rails[i - 1].lenght; // - (rails[i - 1].width * 1); } } vb_RedRail[i] = new VertexBuffer(typeof(CustomVertex.PositionColored), 4, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default); vertices = new CustomVertex.PositionColored[4]; // make a thing with four verts vertices[0].Color = Color.Red.ToArgb(); vertices[1].Color = Color.Red.ToArgb(); vertices[2].Color = Color.Red.ToArgb(); vertices[3].Color = Color.Red.ToArgb(); if (i == 100) { vertices[0].Position = new Vector3(1100, 1100, 0f); vertices[1].Position = new Vector3(1100, 10000, 0f); vertices[2].Position = new Vector3(10000, 1100, 0f); vertices[3].Position = new Vector3(10000, 10000, 0f); } else if (rails[i].directionOfTravel == (int)ClassDef.clsRail.direction.right) { vertices[0].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y, 0f); vertices[1].Position = new Vector3(rails[i].start_Loc_x - rails[i].lenght, rails[i].start_Loc_y, 0f); vertices[2].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y - (rails[i].width * 2), 0f); vertices[3].Position = new Vector3(rails[i].start_Loc_x - rails[i].lenght, rails[i].start_Loc_y - (rails[i].width * 2), 0f); } else if (rails[i].directionOfTravel == (int)ClassDef.clsRail.direction.left) { vertices[0].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y, 0f); vertices[1].Position = new Vector3(rails[i].start_Loc_x + rails[i].lenght, rails[i].start_Loc_y, 0f); vertices[2].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y + (rails[i].width * 2), 0f); vertices[3].Position = new Vector3(rails[i].start_Loc_x + rails[i].lenght, rails[i].start_Loc_y + (rails[i].width * 2), 0f); } else if (rails[i].directionOfTravel == (int)ClassDef.clsRail.direction.up) { vertices[0].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y, 0f); vertices[1].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y + rails[i].lenght, 0f); vertices[2].Position = new Vector3(rails[i].start_Loc_x - (rails[i].width * 2), rails[i].start_Loc_y, 0f); vertices[3].Position = new Vector3(rails[i].start_Loc_x - (rails[i].width * 2), rails[i].start_Loc_y + rails[i].lenght, 0f); } else if (rails[i].directionOfTravel == (int)ClassDef.clsRail.direction.down) { vertices[0].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y, 0f); vertices[1].Position = new Vector3(rails[i].start_Loc_x, rails[i].start_Loc_y - rails[i].lenght, 0f); vertices[2].Position = new Vector3(rails[i].start_Loc_x - (rails[i].width * 2), rails[i].start_Loc_y, 0f); vertices[3].Position = new Vector3(rails[i].start_Loc_x - (rails[i].width * 2), rails[i].start_Loc_y - rails[i].lenght, 0f); } vb_RedRail[i].SetData(vertices, 0, LockFlags.None); } }
protected static int ToPointsBuffer ( Rhino.Geometry.PointCloud pointCloud, Primitive.Part part, out VertexFormatBits vertexFormatBits, out VertexBuffer vb, out int vertexCount, out IndexBuffer ib ) { int pointsCount = part.VertexCount; int normalCount = pointCloud.ContainsNormals ? pointsCount : 0; int colorsCount = pointCloud.ContainsColors ? pointsCount : 0; bool hasPoints = pointsCount > 0; bool hasNormals = normalCount == pointsCount; bool hasColors = colorsCount == pointsCount; if (hasPoints) { if (hasNormals) { if (hasColors) { vertexFormatBits = VertexFormatBits.PositionNormalColored; vb = new VertexBuffer(pointsCount * VertexPositionNormalColored.GetSizeInFloats()); vb.Map(pointsCount * VertexPositionNormalColored.GetSizeInFloats()); using (var vstream = vb.GetVertexStreamPositionNormalColored()) { for (int p = part.StartVertexIndex; p < part.EndVertexIndex; ++p) { var point = pointCloud[p]; var c = new ColorWithTransparency(point.Color.R, point.Color.G, point.Color.B, 255u - point.Color.A); vstream.AddVertex(new VertexPositionNormalColored(point.Location.ToHost(), point.Normal.ToHost(), c)); } } vb.Unmap(); } else { vertexFormatBits = VertexFormatBits.PositionNormal; vb = new VertexBuffer(pointsCount * VertexPositionNormal.GetSizeInFloats()); vb.Map(pointsCount * VertexPositionNormal.GetSizeInFloats()); using (var vstream = vb.GetVertexStreamPositionNormal()) { for (int p = part.StartVertexIndex; p < part.EndVertexIndex; ++p) { var point = pointCloud[p]; vstream.AddVertex(new VertexPositionNormal(point.Location.ToHost(), point.Normal.ToHost())); } } vb.Unmap(); } } else { if (hasColors) { vertexFormatBits = VertexFormatBits.PositionColored; vb = new VertexBuffer(pointsCount * VertexPositionColored.GetSizeInFloats()); vb.Map(pointsCount * VertexPositionColored.GetSizeInFloats()); using (var vstream = vb.GetVertexStreamPositionColored()) { for (int p = part.StartVertexIndex; p < part.EndVertexIndex; ++p) { var point = pointCloud[p]; var c = new ColorWithTransparency(point.Color.R, point.Color.G, point.Color.B, 255u - point.Color.A); vstream.AddVertex(new VertexPositionColored(point.Location.ToHost(), c)); } } vb.Unmap(); } else { vertexFormatBits = VertexFormatBits.Position; vb = new VertexBuffer(pointsCount * VertexPosition.GetSizeInFloats()); vb.Map(pointsCount * VertexPosition.GetSizeInFloats()); using (var vstream = vb.GetVertexStreamPosition()) { for (int p = part.StartVertexIndex; p < part.EndVertexIndex; ++p) { var point = pointCloud[p]; vstream.AddVertex(new VertexPosition(point.Location.ToHost())); } } vb.Unmap(); } } ib = IndexPointsBuffer(pointsCount); } else { vertexFormatBits = 0; vb = null; ib = null; } vertexCount = pointsCount; return(pointsCount); }
public void SetVertexBuffer(uint index, VertexBuffer vb) { NoAllocSetVertexBufferEntry entry = new NoAllocSetVertexBufferEntry(index, vb); AddEntry(SetVertexBufferEntryID, ref entry); }
public void RenderViews(ViewportInfo viewportInfo, Scene scene) { #if MEASURE_TIMES DateTime ts = DateTime.Now; DateTime t1 = DateTime.Now; #endif if (pp.BackBufferWidth != viewportInfo.resX || pp.BackBufferHeight != viewportInfo.resY) { pp = new PresentParameters(); pp.SwapEffect = SwapEffect.Discard; pp.Windowed = true; pp.BackBufferWidth = viewportInfo.resX; pp.BackBufferHeight = viewportInfo.resY; pp.BackBufferFormat = Format.A8R8G8B8; if (d3d != null) { d3d.Dispose(); } if (device != null) { device.Dispose(); } d3d = new Direct3D(); device = new Device(d3d, 0, DeviceType.Hardware, handle, CreateFlags.HardwareVertexProcessing, pp); } #if MEASURE_TIMES DateTime t2 = DateTime.Now; TimeSpan t = t2 - t1; w.WriteLine("Tworzenie device'a " + t.Milliseconds); #endif //selectionTex = Texture.FromFile(device, "..\\..\\selectionTex.png"); #if MEASURE_TIMES t1 = DateTime.Now; device.SetRenderState(RenderState.Lighting, true); #endif int l = 0; if (scene.lights.Count == 0) { device.SetLight(0, defLight); device.EnableLight(0, true); device.EnableLight(1, false); } else { foreach (Light_ light_ in scene.lights) { Light light = new Light(); light.Diffuse = new Color4(light_.colorR, light_.colorG, light_.colorB); light.Position = light_.position; light.Range = 100; light.Attenuation0 = 10.0f / light_.power; if (light_.type == Light_Type.Point) { light.Type = LightType.Point; } else { light.Type = LightType.Spot; } light.Direction = light_.direction; device.SetLight(l, light); device.EnableLight(l, true); l++; } device.EnableLight(l + 1, false); } #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Tworzenie świateł " + t.Milliseconds); t1 = DateTime.Now; #endif device.SetRenderState(RenderState.FillMode, wireframe ? FillMode.Wireframe : FillMode.Solid); device.SetRenderState(RenderState.CullMode, Cull.Clockwise); device.SetRenderState(RenderState.ShadeMode, ShadeMode.Flat); #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("SetRenderState " + t.Milliseconds); t1 = DateTime.Now; #endif //Vertex[] vertices = new Vertex[scene.points.Count]; //List<int>[] vertexTriangle = new List<int>[scene.points.Count]; //Parallel.For(0, vertexTriangle.Length, index => vertexTriangle[index] = new List<int>()); ///*for(int i = 0; i < vertexTriangle.Length; ++i) //{ // vertexTriangle[i] = new List<int>(); //}*/ //int[] indices = new int[3 * scene.triangles.Count]; //int[] selIndices = new int[3 * scene.triangles.Count]; //uint numIndices = 0; //uint numSelIndices = 0; bool[] selPoints = new bool[scene.points.Count]; Parallel.For(0, selPoints.Length, index => selPoints[index] = false); /*for(int i = 0; i < selPoints.Length; ++i) * { * selPoints[i] = false; * }*/ bool[] selected = scene.GetSelectedTriangles(); #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("t1 " + t.Milliseconds); t1 = DateTime.Now; #endif for (int i = 0; i < scene.triangles.Count; ++i) { Triangle triangle = scene.triangles[i]; //if (selected[i] == false) //{ // scene.indices[numIndices] = (int)triangle.p1; // scene.indices[numIndices + 1] = (int)triangle.p3; // scene.indices[numIndices + 2] = (int)triangle.p2; // numIndices += 3; //} //else if (selected[i]) { //scene.selIndices[numSelIndices] = (int)triangle.p1; //scene.selIndices[numSelIndices + 1] = (int)triangle.p3; //scene.selIndices[numSelIndices + 2] = (int)triangle.p2; selPoints[triangle.p1] = true; selPoints[triangle.p2] = true; selPoints[triangle.p3] = true; //numSelIndices += 3; } //scene.vertexTriangle[triangle.p1].Add(i); //scene.vertexTriangle[triangle.p2].Add(i); //scene.vertexTriangle[triangle.p3].Add(i); } #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("t2 " + t.Milliseconds); t1 = DateTime.Now; #endif for (int i = 0; i < scene.points.Count; ++i) { if (selPoints[i] || scene.normals.Count <= i) { Vector3D normal = new Vector3D(); foreach (int face in scene.vertexTriangle[i]) { normal += Utilities.CalculateNormal(scene.points[(int)scene.triangles[face].p3], scene.points[(int)scene.triangles[face].p2], scene.points[(int)scene.triangles[face].p1]); } normal.Normalize(); if (scene.normals.Count <= i) { scene.normals.Add(normal); } else { scene.normals[i] = normal; } } } #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Liczenie normalnych " + t.Milliseconds); t1 = DateTime.Now; #endif Dictionary <string, int> matNames = new Dictionary <string, int>(); for (int i = 0; i < scene.materials.Count; ++i) { matNames.Add(scene.materials[i].name, i); } int[] trPart = new int[scene.triangles.Count]; for (int i = 0; i < scene.parts.Count; ++i) { for (int j = 0; j < scene.parts[i].triangles.Count; ++j) { trPart[scene.parts[i].triangles[j]] = i; } } for (int i = 0; i < scene.vertices.Length; ++i) { int partIndex = trPart[scene.vertexTriangle[i][0]]; String matName = scene.materialAssign[partIndex]; Material_ material = scene.materials[matNames[matName]]; Vector3D point = scene.points[i]; scene.vertices[i].Position = new Vector3(point.x, point.y, point.z); scene.vertices[i].Normal = new Vector3(scene.normals[i].x, scene.normals[i].y, scene.normals[i].z); scene.vertices[i].Color = Color.FromArgb((int)(255 * material.colorR), (int)(255 * material.colorG), (int)(255 * material.colorB)).ToArgb(); scene.vertices[i].tex0 = 0; scene.vertices[i].tex1 = 0; } #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Znajdowanie części i przyp. wierz. " + t.Milliseconds); t1 = DateTime.Now; #endif Mesh mesh = scene.numIndices >= 3 ? new Mesh(device, (int)scene.numIndices / 3, scene.points.Count, MeshFlags.Managed | MeshFlags.Use32Bit, vertexElems) : null; VertexBuffer vb = mesh != null ? mesh.VertexBuffer : null; IndexBuffer ib = mesh != null ? mesh.IndexBuffer : null; #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Tworzenie mesh1 " + t.Milliseconds); t1 = DateTime.Now; #endif if (mesh != null) { vb.Lock(0, 0, LockFlags.None).WriteRange(scene.vertices); vb.Unlock(); ib.Lock(0, 0, LockFlags.None).WriteRange(scene.indices, 0, (int)scene.numIndices); ib.Unlock(); #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Kopiowanie buforów mesh1 " + t.Milliseconds); #endif } #if MEASURE_TIMES t1 = DateTime.Now; #endif Mesh selMesh = scene.numSelIndices >= 3 ? new Mesh(device, (int)scene.numSelIndices / 3, scene.points.Count, MeshFlags.Managed | MeshFlags.Use32Bit, vertexElems) : null; VertexBuffer selvb = selMesh != null ? selMesh.VertexBuffer : null; IndexBuffer selib = selMesh != null ? selMesh.IndexBuffer : null; #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Tworzenie mesh2 " + t.Milliseconds); t1 = DateTime.Now; #endif if (selMesh != null) { selvb.Lock(0, 0, LockFlags.None).WriteRange(scene.vertices); selvb.Unlock(); selib.Lock(0, 0, LockFlags.None).WriteRange(scene.selIndices, 0, (int)scene.numSelIndices); selib.Unlock(); #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Kopiowanie buforów mesh2 " + t.Milliseconds); #endif } #if MEASURE_TIMES t1 = DateTime.Now; #endif device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); if (perspective.X != viewportInfo.posX[0] || perspective.Y != viewportInfo.posY[0] || perspective.Width != viewportInfo.sizeX[0] || perspective.Height != viewportInfo.sizeY[0]) { perspective = new Viewport(); perspective.X = viewportInfo.posX[0]; perspective.Y = viewportInfo.posY[0]; perspective.Width = viewportInfo.sizeX[0]; perspective.Height = viewportInfo.sizeY[0]; perspective.MinZ = 0; perspective.MaxZ = 1; } if (top.X != viewportInfo.posX[1] || top.Y != viewportInfo.posY[1] || top.Width != viewportInfo.sizeX[1] || top.Height != viewportInfo.sizeY[1]) { top = new Viewport(); top.X = viewportInfo.posX[1]; top.Y = viewportInfo.posY[1]; top.Width = viewportInfo.sizeX[1]; top.Height = viewportInfo.sizeY[1]; top.MinZ = 0; top.MaxZ = 1; } if (front.X != viewportInfo.posX[2] || front.Y != viewportInfo.posY[2] || front.Width != viewportInfo.sizeX[2] || front.Height != viewportInfo.sizeY[2]) { front = new Viewport(); front.X = viewportInfo.posX[2]; front.Y = viewportInfo.posY[2]; front.Width = viewportInfo.sizeX[2]; front.Height = viewportInfo.sizeY[2]; front.MinZ = 0; front.MaxZ = 1; } if (side.X != viewportInfo.posX[3] || side.Y != viewportInfo.posY[3] || side.Width != viewportInfo.sizeX[3] || side.Height != viewportInfo.sizeY[3]) { side = new Viewport(); side.X = viewportInfo.posX[3]; side.Y = viewportInfo.posY[3]; side.Width = viewportInfo.sizeX[3]; side.Height = viewportInfo.sizeY[3]; side.MinZ = 0; side.MaxZ = 1; } #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Modyfikacja viewport'ów " + t.Milliseconds); t1 = DateTime.Now; #endif if (perspective.Width > 0 && perspective.Height > 0) { device.Viewport = perspective; float camRotAngle = scene.cams.ElementAt(scene.activeCamera).rotateAngle; float aspect = (float)perspective.Width / perspective.Height; float angle = 2.0f * (float)Math.Atan(Math.Tan(Utilities.DegToRad(scene.cams.ElementAt(scene.activeCamera).fovAngle) / 2.0f) / aspect); device.SetTransform(TransformState.View, Matrix.LookAtRH( scene.cams[scene.activeCamera].position, scene.cams[scene.activeCamera].lookAt, Utilities.RotatePointAroundVector(new Vector3(0, 1, 0), Vector3.Normalize(scene.cams[scene.activeCamera].lookAt - scene.cams[scene.activeCamera].position), camRotAngle))); device.SetTransform(TransformState.Projection, Matrix.PerspectiveFovRH( angle, aspect, 0.01f, 20000)); device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.FromArgb(230, 230, 230), 1.0f, 0); device.BeginScene(); if (mesh != null) { mesh.DrawSubset(0); } //device.SetTexture(0, selectionTex); device.SetRenderState(RenderState.Lighting, false); if (selMesh != null) { selMesh.DrawSubset(0); } device.SetRenderState(RenderState.Lighting, true); //device.SetTexture(0, null); device.EndScene(); } if (top.Width > 0 && top.Height > 0) { device.Viewport = top; device.SetTransform(TransformState.View, Matrix.LookAtRH( orthoPos[0], orthoLookAt[0], new Vector3(0, 1, 0))); device.SetTransform(TransformState.Projection, Matrix.OrthoRH( orthoWidht[0], (float)(top.Height) / top.Width * orthoWidht[0], 0.01f, 20000)); device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.FromArgb(230, 230, 230), 1.0f, 0); device.BeginScene(); if (mesh != null) { mesh.DrawSubset(0); } //device.SetTexture(0, selectionTex); device.SetRenderState(RenderState.Lighting, false); if (selMesh != null) { selMesh.DrawSubset(0); } device.SetRenderState(RenderState.Lighting, true); //device.SetTexture(0, null); device.EndScene(); } if (front.Width > 0 && front.Height > 0) { device.Viewport = front; device.SetTransform(TransformState.View, Matrix.LookAtRH( orthoPos[1], orthoLookAt[1], new Vector3(0, 1, 0))); device.SetTransform(TransformState.Projection, Matrix.OrthoRH( orthoWidht[1], (float)(front.Height) / front.Width * orthoWidht[1], 0.01f, 20000)); device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.FromArgb(230, 230, 230), 1.0f, 0); device.BeginScene(); if (mesh != null) { mesh.DrawSubset(0); } //device.SetTexture(0, selectionTex); device.SetRenderState(RenderState.Lighting, false); if (selMesh != null) { selMesh.DrawSubset(0); } device.SetRenderState(RenderState.Lighting, true); //device.SetTexture(0, null); device.EndScene(); } if (side.Width > 0 && side.Height > 0) { device.Viewport = side; device.SetTransform(TransformState.View, Matrix.LookAtRH( orthoPos[2], orthoLookAt[2], new Vector3(0, 1, 0))); device.SetTransform(TransformState.Projection, Matrix.OrthoRH( orthoWidht[2], (float)(side.Height) / side.Width * orthoWidht[2], 0.01f, 20000)); device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.FromArgb(230, 230, 230), 1.0f, 0); device.BeginScene(); if (mesh != null) { mesh.DrawSubset(0); } //device.SetTexture(0, selectionTex); device.SetRenderState(RenderState.Lighting, false); if (selMesh != null) { selMesh.DrawSubset(0); } device.SetRenderState(RenderState.Lighting, true); //device.SetTexture(0, null); device.EndScene(); } #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Renderowanie " + t.Milliseconds); t1 = DateTime.Now; #endif device.Present(); #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Present " + t.Milliseconds); t1 = DateTime.Now; #endif //selectionTex.Dispose(); if (selMesh != null) { selvb.Dispose(); selib.Dispose(); selMesh.Dispose(); } if (mesh != null) { vb.Dispose(); ib.Dispose(); mesh.Dispose(); } #if MEASURE_TIMES t2 = DateTime.Now; t = t2 - t1; w.WriteLine("Czyszczenie " + t.Milliseconds); DateTime te = DateTime.Now; t = te - ts; w.WriteLine("Całość " + t.Milliseconds); w.WriteLine("-----------------------------------------------------------------"); w.WriteLine(); w.WriteLine(); w.WriteLine(); #endif }
private void GenerateGeometry() { Vector3 posTemp = this.GameObj.Transform.Pos; int count = this.spritePositions.Count; this.vertices.Count = count * 4; ColorRgba mainClr = ColorRgba.White; Rect spriteRect = Rect.Align(Alignment.Center, 0.0f, 0.0f, 64.0f, 64.0f); Rect uvRect = new Rect(this.sharedMaterial.MainTexture.Res.UVRatio); float left = uvRect.X; float right = uvRect.RightX; float top = uvRect.Y; float bottom = uvRect.BottomY; VertexC1P3T2[] vert = this.vertices.Data; Vector3[] pos = this.spritePositions.Data; float[] angle = this.spriteAngles.Data; for (int i = 0; i < count; i++) { Vector2 edge1 = spriteRect.TopLeft; Vector2 edge2 = spriteRect.BottomLeft; Vector2 edge3 = spriteRect.BottomRight; Vector2 edge4 = spriteRect.TopRight; Vector2 spriteXDot, spriteYDot; MathF.GetTransformDotVec(angle[i], out spriteXDot, out spriteYDot); MathF.TransformDotVec(ref edge1, ref spriteXDot, ref spriteYDot); MathF.TransformDotVec(ref edge2, ref spriteXDot, ref spriteYDot); MathF.TransformDotVec(ref edge3, ref spriteXDot, ref spriteYDot); MathF.TransformDotVec(ref edge4, ref spriteXDot, ref spriteYDot); vert[i * 4 + 0].Pos.X = posTemp.X + (pos[i].X + edge1.X); vert[i * 4 + 0].Pos.Y = posTemp.Y + (pos[i].Y + edge1.Y); vert[i * 4 + 0].Pos.Z = posTemp.Z + pos[i].Z; vert[i * 4 + 0].TexCoord.X = left; vert[i * 4 + 0].TexCoord.Y = top; vert[i * 4 + 0].Color = mainClr; vert[i * 4 + 1].Pos.X = posTemp.X + (pos[i].X + edge2.X); vert[i * 4 + 1].Pos.Y = posTemp.Y + (pos[i].Y + edge2.Y); vert[i * 4 + 1].Pos.Z = posTemp.Z + pos[i].Z; vert[i * 4 + 1].TexCoord.X = left; vert[i * 4 + 1].TexCoord.Y = bottom; vert[i * 4 + 1].Color = mainClr; vert[i * 4 + 2].Pos.X = posTemp.X + (pos[i].X + edge3.X); vert[i * 4 + 2].Pos.Y = posTemp.Y + (pos[i].Y + edge3.Y); vert[i * 4 + 2].Pos.Z = posTemp.Z + pos[i].Z; vert[i * 4 + 2].TexCoord.X = right; vert[i * 4 + 2].TexCoord.Y = bottom; vert[i * 4 + 2].Color = mainClr; vert[i * 4 + 3].Pos.X = posTemp.X + (pos[i].X + edge4.X); vert[i * 4 + 3].Pos.Y = posTemp.Y + (pos[i].Y + edge4.Y); vert[i * 4 + 3].Pos.Z = posTemp.Z + pos[i].Z; vert[i * 4 + 3].TexCoord.X = right; vert[i * 4 + 3].TexCoord.Y = top; vert[i * 4 + 3].Color = mainClr; } // Upload vertices to the GPU if (this.geometry == null) { this.geometry = new VertexBuffer(); } this.geometry.LoadVertexData(vert, 0, count * 4); // Prepare a static drawing batch we can re-use this.batch = new DrawBatch( this.geometry, new RawList <VertexDrawRange>() { new VertexDrawRange(0, count * 4) }, VertexMode.Quads, this.sharedMaterial); }
// Create buffers private void CreateBoundingBoxBuffers(BoundingBoxComponent bbc) { bbc.PrimitiveCount = 24; bbc.VertexCount = 48; VertexBuffer vertexBuffer = new VertexBuffer( bbc.GraphicsDevice, typeof(VertexPositionColor), bbc.VertexCount, BufferUsage.WriteOnly); List <VertexPositionColor> vertices = new List <VertexPositionColor>(); const float ratio = 5.0f; Color c = Color.Red; Vector3 xOffset = new Vector3((bbc.BoundingBox.Max.X - bbc.BoundingBox.Min.X) / ratio, 0, 0); Vector3 yOffset = new Vector3(0, (bbc.BoundingBox.Max.Y - bbc.BoundingBox.Min.Y) / ratio, 0); Vector3 zOffset = new Vector3(0, 0, (bbc.BoundingBox.Max.Z - bbc.BoundingBox.Min.Z) / ratio); Vector3[] corners = bbc.BoundingBox.GetCorners(); // Corner 1. vertices.Add(new VertexPositionColor(corners[0], c)); vertices.Add(new VertexPositionColor(corners[0] + xOffset, c)); vertices.Add(new VertexPositionColor(corners[0], c)); vertices.Add(new VertexPositionColor(corners[0] - yOffset, c)); vertices.Add(new VertexPositionColor(corners[0], c)); vertices.Add(new VertexPositionColor(corners[0] - zOffset, c)); // Corner 2. vertices.Add(new VertexPositionColor(corners[1], c)); vertices.Add(new VertexPositionColor(corners[1] - xOffset, c)); vertices.Add(new VertexPositionColor(corners[1], c)); vertices.Add(new VertexPositionColor(corners[1] - yOffset, c)); vertices.Add(new VertexPositionColor(corners[1], c)); vertices.Add(new VertexPositionColor(corners[1] - zOffset, c)); // Corner 3. vertices.Add(new VertexPositionColor(corners[2], c)); vertices.Add(new VertexPositionColor(corners[2] - xOffset, c)); vertices.Add(new VertexPositionColor(corners[2], c)); vertices.Add(new VertexPositionColor(corners[2] + yOffset, c)); vertices.Add(new VertexPositionColor(corners[2], c)); vertices.Add(new VertexPositionColor(corners[2] - zOffset, c)); // Corner 4. vertices.Add(new VertexPositionColor(corners[3], c)); vertices.Add(new VertexPositionColor(corners[3] + xOffset, c)); vertices.Add(new VertexPositionColor(corners[3], c)); vertices.Add(new VertexPositionColor(corners[3] + yOffset, c)); vertices.Add(new VertexPositionColor(corners[3], c)); vertices.Add(new VertexPositionColor(corners[3] - zOffset, c)); // Corner 5. vertices.Add(new VertexPositionColor(corners[4], c)); vertices.Add(new VertexPositionColor(corners[4] + xOffset, c)); vertices.Add(new VertexPositionColor(corners[4], c)); vertices.Add(new VertexPositionColor(corners[4] - yOffset, c)); vertices.Add(new VertexPositionColor(corners[4], c)); vertices.Add(new VertexPositionColor(corners[4] + zOffset, c)); // Corner 6. vertices.Add(new VertexPositionColor(corners[5], c)); vertices.Add(new VertexPositionColor(corners[5] - xOffset, c)); vertices.Add(new VertexPositionColor(corners[5], c)); vertices.Add(new VertexPositionColor(corners[5] - yOffset, c)); vertices.Add(new VertexPositionColor(corners[5], c)); vertices.Add(new VertexPositionColor(corners[5] + zOffset, c)); // Corner 7. vertices.Add(new VertexPositionColor(corners[6], c)); vertices.Add(new VertexPositionColor(corners[6] - xOffset, c)); vertices.Add(new VertexPositionColor(corners[6], c)); vertices.Add(new VertexPositionColor(corners[6] + yOffset, c)); vertices.Add(new VertexPositionColor(corners[6], c)); vertices.Add(new VertexPositionColor(corners[6] + zOffset, c)); // Corner 8. vertices.Add(new VertexPositionColor(corners[7], c)); vertices.Add(new VertexPositionColor(corners[7] + xOffset, c)); vertices.Add(new VertexPositionColor(corners[7], c)); vertices.Add(new VertexPositionColor(corners[7] + yOffset, c)); vertices.Add(new VertexPositionColor(corners[7], c)); vertices.Add(new VertexPositionColor(corners[7] + zOffset, c)); vertexBuffer.SetData(vertices.ToArray()); bbc.Vertices = vertexBuffer; }
protected static VertexBuffer ToVertexBuffer ( Rhino.Geometry.Mesh mesh, Primitive.Part part, out VertexFormatBits vertexFormatBits, System.Drawing.Color color = default(System.Drawing.Color) ) { int verticesCount = part.EndVertexIndex - part.StartVertexIndex; int normalCount = mesh.Normals.Count == mesh.Vertices.Count ? verticesCount : 0; int colorsCount = color.IsEmpty ? (mesh.VertexColors.Count == mesh.Vertices.Count ? verticesCount : 0) : verticesCount; bool hasVertices = verticesCount > 0; bool hasNormals = normalCount > 0; bool hasColors = colorsCount > 0; if (hasVertices) { var vertices = mesh.Vertices; if (hasNormals) { var normals = mesh.Normals; if (hasColors) { vertexFormatBits = VertexFormatBits.PositionNormalColored; var colors = mesh.VertexColors; var vb = new VertexBuffer(verticesCount * VertexPositionNormalColored.GetSizeInFloats()); vb.Map(verticesCount * VertexPositionNormalColored.GetSizeInFloats()); using (var stream = vb.GetVertexStreamPositionNormalColored()) { for (int v = part.StartVertexIndex; v < part.EndVertexIndex; ++v) { var c = !color.IsEmpty ? color : colors[v]; stream.AddVertex(new VertexPositionNormalColored(vertices[v].ToHost(), normals[v].ToHost(), new ColorWithTransparency(c.R, c.G, c.B, 255u - c.A))); } } vb.Unmap(); return(vb); } else { vertexFormatBits = VertexFormatBits.PositionNormal; var vb = new VertexBuffer(verticesCount * VertexPositionNormal.GetSizeInFloats()); vb.Map(verticesCount * VertexPositionNormal.GetSizeInFloats()); using (var stream = vb.GetVertexStreamPositionNormal()) { for (int v = part.StartVertexIndex; v < part.EndVertexIndex; ++v) { stream.AddVertex(new VertexPositionNormal(vertices[v].ToHost(), normals[v].ToHost())); } } vb.Unmap(); return(vb); } } else { if (hasColors) { vertexFormatBits = VertexFormatBits.PositionColored; var colors = mesh.VertexColors; var vb = new VertexBuffer(verticesCount * VertexPositionColored.GetSizeInFloats()); vb.Map(verticesCount * VertexPositionColored.GetSizeInFloats()); using (var stream = vb.GetVertexStreamPositionColored()) { for (int v = part.StartVertexIndex; v < part.EndVertexIndex; ++v) { var c = !color.IsEmpty ? color : colors[v]; stream.AddVertex(new VertexPositionColored(vertices[v].ToHost(), new ColorWithTransparency(c.R, c.G, c.B, 255u - c.A))); } } vb.Unmap(); return(vb); } else { vertexFormatBits = VertexFormatBits.Position; var vb = new VertexBuffer(verticesCount * VertexPosition.GetSizeInFloats()); vb.Map(verticesCount * VertexPosition.GetSizeInFloats()); using (var stream = vb.GetVertexStreamPosition()) { for (int v = part.StartVertexIndex; v < part.EndVertexIndex; ++v) { stream.AddVertex(new VertexPosition(vertices[v].ToHost())); } } vb.Unmap(); return(vb); } } } vertexFormatBits = 0; return(null); }