me.fier.engine/modules/engine/frontend/generic/textures.c

79 lines
2.8 KiB
C
Raw Normal View History

2023-05-14 10:21:03 +00:00
// Mostly for fun (but can very slightly increase performance for large textures). If set to 1, does not clear texture's affiliated and leaves garbage.
#define ENGINE_GENERIC_TEXTURE_NOCLEAR 1
struct ENGINE_TEXTURE { int width; int height; void * fe_texture; };
struct ENGINE_GENERIC_TEXTURE { char * pixels; };
struct ENGINE_TEXTURE * engine_createTexture(int width,int height) {
// frontend texture
char * pixels = engine_malloc(NULL,sizeof(char) * width * height * 4);
#if (ENGINE_GENERIC_TEXTURE_NOCLEAR == 0)
memset(pixels,0,sizeof(char) * width * height * 4);
#endif
struct ENGINE_GENERIC_TEXTURE * fe_texture = engine_malloc(NULL,sizeof(struct ENGINE_GENERIC_TEXTURE));
fe_texture->pixels = pixels;
// engine texture
struct ENGINE_TEXTURE * texture = engine_malloc(NULL,sizeof(struct ENGINE_TEXTURE));
texture->width = width;
texture->height = height;
texture->fe_texture = (void *)fe_texture;
return texture;
}
struct ENGINE_GENERIC_TEXTURE_COLOR { char r; char g; char b; char a; };
struct ENGINE_GENERIC_TEXTURE_COLOR engine_generic_texture_color;
void engine_textureSetColor(char r,char g,char b,char a) {
engine_generic_texture_color.r = r;
engine_generic_texture_color.g = g;
engine_generic_texture_color.b = b;
engine_generic_texture_color.a = a;
}
void engine_textureDrawPixel(struct ENGINE_TEXTURE * texture,int x,int y) {
char * pixels = ((struct ENGINE_GENERIC_TEXTURE *)(texture->fe_texture))->pixels;
long pixelIndex = (x + y * texture->width) * 4;
pixels[pixelIndex + 0] = engine_generic_texture_color.r;
pixels[pixelIndex + 1] = engine_generic_texture_color.g;
pixels[pixelIndex + 2] = engine_generic_texture_color.b;
pixels[pixelIndex + 3] = engine_generic_texture_color.a;
}
void engine_textureDestroy(struct ENGINE_TEXTURE * texture) {
struct ENGINE_GENERIC_TEXTURE * fe_texture = (struct ENGINE_GENERIC_TEXTURE *)(texture->fe_texture);
engine_free(fe_texture->pixels);
engine_free(fe_texture);
engine_free(texture);
}
void engine_renderTexture2D(struct ENGINE_TEXTURE * texture,int sx,int sy) {
char * pixels = ((struct ENGINE_GENERIC_TEXTURE *)(texture->fe_texture))->pixels;
int ex = sx + texture->width;
if (ex > engine_width) { ex = engine_width; }
int ey = sy + texture->height;
if (ey > engine_width) { ey = engine_height; }
int x = sx;
if (x < 0) { x = 0; }
int y = sy;
if (y < 0) { y = 0; }
long pixelIndex = 0;
while (y < ey) {
while (x < ex) {
pixelIndex = ((x - sx) + (y - sy) * texture->width)*4;
engine_setColor(pixels[pixelIndex],pixels[pixelIndex + 1],pixels[pixelIndex + 2],pixels[pixelIndex + 3]);
engine_drawPixel(x,y);
++x;
}
x = sx;
++y;
}
}
void engine_fileToTexture(struct ENGINE_TEXTURE * texture,char * fpath) {
FILE * f = fopen(fpath,"r");
fgets(((struct ENGINE_GENERIC_TEXTURE *)(texture->fe_texture))->pixels,texture->width * texture->height,f);
fclose(f);
}