/*
 * TextureLoader.cpp
 *
 *  Created on: 15 nov. 2020
 *      Author: simon
 */

#include "client/render/loader/TextureLoader.h"
#define STB_IMAGE_IMPLEMENTATION
#include "client/render/loader/stb_image.h"
#include <iostream>
#include "client/render/GL.h"

namespace TextureLoader {

unsigned int LoadGLTexture(const char* fileName) {

	int width, height, comp;

	const unsigned char* image = stbi_load(fileName, &width, &height, &comp, STBI_rgb_alpha);

	if (image == nullptr) {
		std::cerr << "Erreur lors du chargement de la texture !" << std::endl;
		throw(std::runtime_error("Failed to load texture"));
	}

	GLuint textureID;
	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D, textureID);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	if (comp == 3)
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
			GL_UNSIGNED_BYTE, image);
	else if (comp == 4)
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
			GL_UNSIGNED_BYTE, image);

	glBindTexture(GL_TEXTURE_2D, 0);
	stbi_image_free((void*)image);
	return textureID;
}

}
