using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using RecrownedAthenaeum.Camera; using System; namespace RecrownedAthenaeum.Render { /// /// Renders rectangles using the . /// public class RectangleRenderer : IDisposable { private bool filled; private bool disposed; /// /// The used. Needs to be disposed. /// private readonly PrimitiveBatch primitiveBatch; /// /// Creates a rectangle renderer with the given . /// /// Camera to use for . Default will use . /// Graphics device to use. Default will use . public RectangleRenderer(Camera2D camera = null, GraphicsDevice graphicsDevice = null) { primitiveBatch = new PrimitiveBatch(camera, graphicsDevice); } /// /// Disposes the rectangle renderer. /// public void Dispose() { Dispose(true); } /// /// Overridable for dispose. /// /// True when its a player calling the dispose. public virtual void Dispose(bool disposing) { if (disposed) throw new ObjectDisposedException(GetType().Name); if (disposing) { primitiveBatch.Dispose(); } disposed = true; } /// /// Begins a batch for rectangles. /// /// Whether or not this batch should be filled rectangles. public void Begin(bool filled = false) { this.filled = filled; primitiveBatch.Begin(filled ? PrimitiveType.TriangleStrip : PrimitiveType.LineStrip); } /// /// Ends the batch. /// public void End() { primitiveBatch.End(); } /// /// Draws a basic rectangle given bottom left and top right. /// /// X coordinate of bottom left. /// Y coordinate of bottom left. /// Width of rectangle. /// Height of rectangle. /// Color of all vertices of this rectangle. /// Rotation of rectangle. Default is 0 radians. /// If this rectangle should be filled. public void Draw(int x, int y, int width, int height, Color color, float rotation = 0) { primitiveBatch.primitiveCount = filled ? 3 : 4; Vector2[] corners = new Vector2[4]; corners[0] = new Vector2(x, y); corners[1] = new Vector2(x + width, y); corners[2] = new Vector2(x + width, y + height); corners[3] = new Vector2(x, y + height); if (rotation != 0) { Matrix rotMat = Matrix.CreateRotationZ(rotation); for (int i = 0; i < corners.Length; i++) { Vector2.Transform(corners[i], rotMat); } } primitiveBatch.AddVertex(corners[0], color); primitiveBatch.AddVertex(corners[1], color); primitiveBatch.AddVertex(corners[2], color); primitiveBatch.AddVertex(corners[3], color); primitiveBatch.AddVertex(corners[0], color); } } }