#include "../../../include/RenderBackend/OpenGL/Texture2D.hpp" #include "../../../include/RenderBackend/OpenGL/opengl.hpp" #include "../../../include/Image.hpp" #include #include namespace amalgine { struct TextureIdAllocator { TextureIdAllocator(){ glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_units); if(max_texture_units < 1) max_texture_units = 1; printf("max texture units: %d\n", max_texture_units); } u32 get_free_texture_id() { if(!free_spots.empty()) { u32 texture_id = free_spots.top(); free_spots.pop(); return texture_id; } if(texture_id_counter + 1 == max_texture_units) { fprintf(stderr, "Error: No free spot left for textures, resetting counter\n"); texture_id_counter = 0; } return texture_id_counter++; } void free_texture_id(i32 texture_id) { free_spots.push(texture_id); } std::stack free_spots; i32 texture_id_counter = 0; i32 max_texture_units = 0; }; static TextureIdAllocator *texture_id_allocator = nullptr; Texture2D::Texture2D(Image *image) { assert(image); if(!texture_id_allocator) texture_id_allocator = new TextureIdAllocator(); texture_id = texture_id_allocator->get_free_texture_id(); glGenTextures(1, &texture_ref); glActiveTexture(GL_TEXTURE0 + texture_id); glBindTexture(GL_TEXTURE_2D, texture_ref); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->getWidth(), image->getHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, image->getData()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); } Texture2D::~Texture2D() { texture_id_allocator->free_texture_id(texture_id); glDeleteTextures(1, &texture_ref); } }