using System; using System.Linq; using Chernobyl.Collections.Generic.Event; using Chernobyl.Graphics.Drawing; using Chernobyl.Graphics.Texture; using Chernobyl.Mathematics; using Microsoft.Xna.Framework.Graphics; namespace Chernobyl.Graphics.Xna.Texture { /// /// Implements an XNA 2D render target. /// public class XnaRenderTarget2D : Drawable, IRenderTarget2D { /// /// Constructor. /// /// The object that holds the services. /// The width of the render target.This must be a /// power of two. /// The height of the render target.This must be a /// power of two. /// The number of mipmap levels to generate. /// See http://en.wikipedia.org/wiki/Mipmap for more information /// about mipmaps. /// The format of the texture (aka, surface). public XnaRenderTarget2D(IEventCollection services, uint width, uint height, uint mipmapLevels, TextureFormat format) { if (Functions.IsPowerOfTwo(width) == false) throw new ArgumentException(WidthHeightPowerOfTwoErrorMsg + "width specified: " + width, "width"); if (Functions.IsPowerOfTwo(height) == false) throw new ArgumentException(WidthHeightPowerOfTwoErrorMsg + "height specified: " + height, "height"); this.GraphicsDevice = services.OfType().First(); RenderTarget = new Microsoft.Xna.Framework.Graphics.RenderTarget2D(this.GraphicsDevice, (int)width, (int)height, (int)mipmapLevels, Utility.ToSurfaceFormat(format)); } /// /// Called before the "Draw" method to apply any states /// or preconditions. /// public override void PreDraw() { // grab the current render target PreviousTarget = this.GraphicsDevice.GetRenderTarget(0); // set this render target this.GraphicsDevice.SetRenderTarget(0, RenderTarget); // clear this render target this.GraphicsDevice.Clear(ClearOptions.Target, Microsoft.Xna.Framework.Graphics.Color.CornflowerBlue, 0, 0); } /// /// Called after the "Draw" method to remove any states /// or preconditions. /// public override void PostDraw() { // switch back to the previous device. this.GraphicsDevice.SetRenderTarget(0, PreviousTarget as Microsoft.Xna.Framework.Graphics.RenderTarget2D); } /// /// The number of mipmaps generated for this render target. /// public uint MipmapLevelsCount { get; private set; } /// /// The width of the render target. /// public uint Width { get; private set; } /// /// The height of the render target. /// public uint Height { get; private set; } /// /// The XNA render target. /// public Microsoft.Xna.Framework.Graphics.RenderTarget2D RenderTarget {get; private set;} /// /// Used to hold the previous target when the new target is set. /// RenderTarget PreviousTarget { get; set; } /// /// The XNA graphics device. /// public GraphicsDevice GraphicsDevice { get; set; } /// /// Error message used when width or height is not a power of two. /// static string WidthHeightPowerOfTwoErrorMsg = "The width and height of a IRenderTarget2D must be powers of two (8, 16, 32, 64, 128, 256, 512, 1024, etc)."; } }