/* * * * * * * * * * * * * * * * * * * * * * * * * * * Renders 2D primitives (lines) specified in screen/pixel space * using a custom shader to transform vertices into clip space. * * By Karn Bianco - www.KarnBianco.co.uk * * * * * * * * * * * * * * * * * * * * * * * * * * */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace YourNameSpaceHere { public class Render2DLines : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; Vector2[] vertices; // Vertices defined in screen space VertexPositionColor[] verticesForGPU; // 3D vertices required for rendering int[] indices; // Indices for defining lines from points Effect lineEffect; // Simple custom shader for rendering lines public Render2DLines() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.graphics.PreferredBackBufferWidth = 450; this.graphics.PreferredBackBufferHeight = 300; } protected override void LoadContent() { // Load effect file using the content pipeline lineEffect = Content.Load("LineShader2D"); // Set up vertices in screen space (just as you would set sprite positions) vertices = new Vector2[4]; vertices[0] = new Vector2(10, 10); vertices[1] = new Vector2(400, 10); vertices[2] = new Vector2(400, 150); vertices[3] = new Vector2(10, 150); // Set up 3D vertices using screen space vectors and a 0 component for z-value verticesForGPU = new VertexPositionColor[4]; for (int i = 0; i < vertices.Length; i++) { verticesForGPU[i].Position = new Vector3(vertices[i], 0); verticesForGPU[i].Color = Color.White; } // Generate two indices for each vertex indices = new int[8] { 0, 1, 1, 2, 2, 3, 3, 0 }; // Set vertex declaration GraphicsDevice.VertexDeclaration = new VertexDeclaration( GraphicsDevice, VertexPositionColor.VertexElements); ; // Set Viewportsize parameter lineEffect.Parameters["ViewportSize"].SetValue(new Vector2 (GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height)); // Set Transform matrix as Idneity matrix by default (can be used to // translate, rotate and scale vertices if required) lineEffect.Parameters["TransformMatrix"].SetValue(Matrix.Identity); } protected override void Update(GameTime gameTime) { base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); lineEffect.Begin(); // Begin using custom effect lineEffect.CurrentTechnique.Passes[0].Begin(); // Only one pass in technique GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.LineList, verticesForGPU, 0, verticesForGPU.Length, indices, 0, indices.Length / 2); // Draw lines lineEffect.CurrentTechnique.Passes[0].End(); lineEffect.End(); base.Draw(gameTime); } } }