Skip to content

Instantly share code, notes, and snippets.

@jessefreeman
Created April 6, 2016 15:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jessefreeman/5b3b03a2b61827ab717823fc99eeafc9 to your computer and use it in GitHub Desktop.
Save jessefreeman/5b3b03a2b61827ab717823fc99eeafc9 to your computer and use it in GitHub Desktop.
A class that emulates the API of Unity's Texture2D but uses int as references to color index instead of the color class.
using System;
namespace PixelVision.Engine.Chips.Graphics.Sprites
{
public interface ITextureData
{
int width { get; }
int height { get; }
int GetPixel(int x, int y);
void SetPixel(int x, int y, int value);
int[] GetPixels();
int[] GetPixels(int x, int y, int blockWidth, int blockHeight);
void SetPixels(int[] pixels);
void SetPixels(int x, int y, int blockWidth, int blockHeight, int[] pixels);
void Resize(int width, int height);
}
public class TextureData : ITextureData
{
protected int[] pixels = new int[0];
public TextureData(int width, int height)
{
Resize(width, height);
}
public int width { get; private set; }
public int height { get; private set; }
public int GetPixel(int x, int y)
{
var index = x + width*y;
return pixels[index];
}
public int[] GetPixels()
{
var total = width*height;
var copy = new int[total];
Array.Copy(pixels, copy, total);
return copy;
}
public int[] GetPixels(int x, int y, int blockWidth, int blockHeight)
{
var total = blockWidth*blockHeight;
var copy = new int[total];
GridLoop(x, y, blockWidth, blockHeight, (index, x1, y1) => { copy[index] = GetPixel(x1, y1); });
return copy;
}
public void SetPixel(int x, int y, int value)
{
var index = x + width * y;
pixels[index] = value;
}
public void SetPixels(int[] pixels)
{
Array.Copy(pixels, this.pixels, pixels.Length);
}
public void SetPixels(int x, int y, int blockWidth, int blockHeight, int[] pixels)
{
GridLoop(x, y, blockWidth, blockHeight, (index,x1, y1) => { SetPixel(x1, y1, pixels[index]); });
}
public void Resize(int width, int height)
{
this.width = width;
this.height = height;
Array.Resize(ref pixels, width*height);
}
protected void GridLoop(int x, int y, int blockWidth, int blockHeight, Action<int, int, int> fn)
{
var total = blockWidth*blockHeight;
int column, newX, newY, row = 0;
var maxColumns = blockWidth - 1;
for (var i = 0; i < total; i++)
{
column = i%blockWidth;
newX = i%blockWidth + x;
newY = row + y;
fn(i, newX, newY);
if (column == maxColumns)
{
row++;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment