-
-
Save benaadams/c019c53bb3da4e7ac78fdee11eca37cc 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
{ | |
private static readonly int[] emptyPixels = new int[0]; | |
protected int[] pixels = emptyPixels; | |
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 blockExtent = blockWidth + x; | |
var copy = new int[blockWidth * blockHeight]; | |
var column = x; | |
var row = y; | |
for (var i = 0; i < copy.Length; i++) | |
{ | |
copy[i] = pixels[column + Width * row]; | |
column++; | |
if (column == blockExtent) | |
{ | |
column = x; | |
row++; | |
} | |
} | |
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) | |
{ | |
var blockExtent = blockWidth + x; | |
var column = x; | |
var row = y; | |
for (var i = 0; i < pixels.Length; i++) | |
{ | |
this.pixels[column + Width * row] = pixels[i]; | |
column++; | |
if (column == blockExtent) | |
{ | |
column = x; | |
row++; | |
} | |
} | |
} | |
public void Resize(int width, int height) | |
{ | |
Width = width; | |
Height = height; | |
Array.Resize(ref pixels, width * height); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment