vigrid

XNA Hacks - Simple Automatic TextureAtlas Helper

Mar 30th, 2012
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1.     public class TextureAtlas
  2.     {
  3.         private readonly Dictionary<Texture2D, Rectangle> _atlasData = new Dictionary<Texture2D, Rectangle>();
  4.  
  5.         private readonly Texture2D _texture;
  6.  
  7.         public Texture2D Texture { get { return _texture; } }
  8.  
  9.         private int _x, _y, _nextY;
  10.  
  11.         public TextureAtlas(GraphicsDevice graphicsDevice, int width, int height)
  12.         {
  13.             _texture = new Texture2D(graphicsDevice, width, height);
  14.         }
  15.  
  16.         public void RegisterTextures(IEnumerable<Texture2D> textures)
  17.         {
  18.             foreach (var texture in textures)
  19.             {
  20.                 RegisterTexture(texture);
  21.             }
  22.         }
  23.  
  24.         public void RegisterTexture(Texture2D texture)
  25.         {
  26.             // NOTE: This is a simple proof-of-concept implementation
  27.             if (_atlasData.ContainsKey(texture))
  28.             {
  29.                 return;
  30.             }
  31.  
  32.             if (texture.Width + _x >= _texture.Width)
  33.             {
  34.                 _x = 0;
  35.                 _y = _nextY;
  36.             }
  37.  
  38.             _atlasData[texture] = BlitTexture(_texture, texture, _x, _y);
  39.  
  40.             _x += texture.Width;
  41.             _nextY = Math.Max(_nextY, _y + texture.Height);
  42.         }
  43.  
  44.         public bool LookUp(Texture2D source, out Texture2D result, out Rectangle textureRectangle)
  45.         {
  46.             textureRectangle = new Rectangle(0, 0, source.Width, source.Height);
  47.  
  48.             if (_atlasData.ContainsKey(source))
  49.             {
  50.                 result = _texture;
  51.                 textureRectangle.X = _atlasData[source].X;
  52.                 textureRectangle.Y = _atlasData[source].Y;
  53.                 return true;
  54.             }
  55.  
  56.             result = source;
  57.             return false;
  58.         }
  59.  
  60.         private Rectangle BlitTexture(Texture2D destinationTexture, Texture2D sourceTexture, int x, int y)
  61.         {
  62.             var buffer = new Color[sourceTexture.Width*sourceTexture.Height];
  63.             sourceTexture.GetData(buffer);
  64.  
  65.             var dest = new Rectangle(x, y, sourceTexture.Width, sourceTexture.Height);
  66.             destinationTexture.SetData(0, dest, buffer, 0, buffer.Length);
  67.  
  68.             return dest;
  69.         }
  70.     }
Add Comment
Please, Sign In to add comment