Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TextureAtlas
- {
- private readonly Dictionary<Texture2D, Rectangle> _atlasData = new Dictionary<Texture2D, Rectangle>();
- private readonly Texture2D _texture;
- public Texture2D Texture { get { return _texture; } }
- private int _x, _y, _nextY;
- public TextureAtlas(GraphicsDevice graphicsDevice, int width, int height)
- {
- _texture = new Texture2D(graphicsDevice, width, height);
- }
- public void RegisterTextures(IEnumerable<Texture2D> textures)
- {
- foreach (var texture in textures)
- {
- RegisterTexture(texture);
- }
- }
- public void RegisterTexture(Texture2D texture)
- {
- // NOTE: This is a simple proof-of-concept implementation
- if (_atlasData.ContainsKey(texture))
- {
- return;
- }
- if (texture.Width + _x >= _texture.Width)
- {
- _x = 0;
- _y = _nextY;
- }
- _atlasData[texture] = BlitTexture(_texture, texture, _x, _y);
- _x += texture.Width;
- _nextY = Math.Max(_nextY, _y + texture.Height);
- }
- public bool LookUp(Texture2D source, out Texture2D result, out Rectangle textureRectangle)
- {
- textureRectangle = new Rectangle(0, 0, source.Width, source.Height);
- if (_atlasData.ContainsKey(source))
- {
- result = _texture;
- textureRectangle.X = _atlasData[source].X;
- textureRectangle.Y = _atlasData[source].Y;
- return true;
- }
- result = source;
- return false;
- }
- private Rectangle BlitTexture(Texture2D destinationTexture, Texture2D sourceTexture, int x, int y)
- {
- var buffer = new Color[sourceTexture.Width*sourceTexture.Height];
- sourceTexture.GetData(buffer);
- var dest = new Rectangle(x, y, sourceTexture.Width, sourceTexture.Height);
- destinationTexture.SetData(0, dest, buffer, 0, buffer.Length);
- return dest;
- }
- }
Add Comment
Please, Sign In to add comment