Overview
TheTextureManager class creates and manages an OpenGL 2D texture array that serves as a texture atlas for block rendering. It handles loading PNG images using stb_image, uploading them to GPU texture layers, and providing texture indices for shader sampling.
Header: src/renderer/texture_manager.h
Constructor
TextureManager
w- Width of each texture in pixelsh- Height of each texture in pixelsmax_tex- Maximum number of textures the array can hold
- Creates a
GL_TEXTURE_2D_ARRAYtexture object - Sets texture filtering based on
Options::MIPMAP_TYPE(min filter) andGL_NEAREST(mag filter) - Enables vertical flip for loaded images via
stbi_set_flip_vertically_on_load(true) - Allocates GPU storage with
glTexImage3D(empty, filled later byadd_texture) - Important: Always binds
texture_arraybefore texture operations to avoid writing to wrong GL objects
Public Members
texture_width
texture_height
max_textures
textures
texture_array
GL_TEXTURE_2D_ARRAY. Used in shader bindings.
Methods
add_texture
texture- Texture name (without path or extension)
- Skips if texture with the same name already exists
- Loads image from
assets/textures/{texture}.pngusing stb_image with 4 channels (RGBA) - Binds
texture_arraybefore upload (critical for shadow map compatibility) - Uploads pixel data to layer index =
textures.size() - 1usingglTexSubImage3D - Frees loaded image data with
stbi_image_free - Outputs success/failure message to console
generate_mipmaps
- Binds
texture_arraybefore generation - Calls
glGenerateMipmap(GL_TEXTURE_2D_ARRAY) - Should be called after all textures are added
get_texture_index
texture- Texture name to look up
- Layer index (0-based) if texture exists
- 0 if texture not found (defaults to first texture)
Implementation Details
OpenGL Texture Array Setup
Texture Loading and Upload
Shadow Map Compatibility
Critical: The TextureManager must always bindtexture_array before calling glTexSubImage3D or glGenerateMipmap. This prevents accidentally uploading block textures into the shadow map when shadows are enabled.
src/renderer/texture_manager.cpp:43 and src/renderer/texture_manager.cpp:26 for explicit bindings.
Unit Test Mode
WhenUNIT_TEST is defined:
- Constructor sets
texture_array = 0and skips GL calls generate_mipmapsand texture upload code paths are skipped- Allows testing texture index logic without OpenGL context
Usage Pattern
Integration with Shaders
Texture array is sampled in shaders using:get_texture_index.
See Also
- Shader - Used to bind texture array to shader samplers
- Block type definitions in
src/renderer/block_type.h - Texture loading from
data/blocks.mccpp World::draw()- Binds texture array before rendering (src/world.cpp)