/src/Texture.cpp
#include "Texture.h"
#include <GLES2/gl2.h>
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>

Texture::Texture(const char* filename) {
	SDL_Surface* img = IMG_Load(filename);
	if (img == 0) {
		fprintf(stderr, "Could not load %s: %s\n", filename, IMG_GetError());
		abort();
	}

	this->w = img->w;
	this->h = img->h;

	SDL_PixelFormat pf;
	pf.palette = NULL;
	pf.BitsPerPixel = 32;
	pf.BytesPerPixel = 4;
	pf.Rmask = 0x000000FF;
	pf.Gmask = 0x0000FF00;
	pf.Bmask = 0x00FF0000;
	pf.Amask = 0xFF000000;
	pf.Rloss = pf.Gloss = pf.Bloss = pf.Aloss = 0;
	pf.Rshift = 24;
	pf.Gshift = 16;
	pf.Bshift = 8;
	pf.Ashift = 0;
	pf.colorkey = 0;
	pf.alpha = 255;
	SDL_Surface *cimg = SDL_ConvertSurface(img, &pf, 0);
	if (cimg == 0) {
		fprintf(stderr, "Could not convert %s to RGBA: %s\n", filename, IMG_GetError());
		abort();
	}
	SDL_FreeSurface(img);

	glActiveTexture(GL_TEXTURE0);
	glGenTextures(1, &this->textureUnit);
	glBindTexture(GL_TEXTURE_2D, this->textureUnit);
	SDL_LockSurface(cimg);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->w, this->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, cimg->pixels);
	SDL_UnlockSurface(cimg);
	GLenum err = glGetError();
	if (err != GL_NO_ERROR) {
		fprintf(stderr, "Error in glTexImage2D: %d\n", err);
		exit(1);
	}
	SDL_FreeSurface(cimg);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}

Texture::~Texture() {
	glDeleteTextures(1, &this->textureUnit);
}

GLuint Texture::getTextureUnit() {
	return this->textureUnit;
}

int Texture::getWidth() {
	return this->w;
}

int Texture::getHeight() {
	return this->h;
}