/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "game/renderer/gl/gl_texture.hpp"

#include "common/logger.hpp"
#include "game/renderer/gl/opengl.hpp"

using namespace polygun::renderer;

GLTexture::GLTexture() :
	m_id(0)
{
	glGenTextures(1, &m_id);
}

GLTexture::~GLTexture() {
	glDeleteTextures(1, &m_id);
}

void GLTexture::bind() {
	glBindTexture(GL_TEXTURE_2D, m_id);
}

bool GLTexture::load_from_pixel_data(const uint8_t* data, unsigned width, unsigned height, unsigned pixel_size) {
	if(width==0 || height==0) 
		return false;
	bind();
	int format;
	switch(pixel_size) {
	case 3:
		format = GL_RGB;
		break;
	case 4:
		format = GL_RGBA;
		break;
	default:
		LOG_ERROR("Invalid pixel size: %d", pixel_size);
		return false;
	}
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, format, GL_UNSIGNED_BYTE, data);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#if defined(RENDERER_GL)
	if(GLEW_ARB_framebuffer_object)
		glGenerateMipmap(GL_TEXTURE_2D);
#endif

	m_width = width;
	m_height = height;

	return true;
}
