Code
uint8_t* pixels = /* Fixed number of pre-generated mipmaps */;
size_t pixels_len = /* length of pixels */;
size_t width = /* width of first mipmap */;
size_t height = /* height of first mipmap */;
assert(pixels_len >= width * height * 4);
unsigned int new_texture;
glGenTextures(1, &new_texture);
glBindTexture(GL_TEXTURE_2D, new_texture);
// Rendered smaller than texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_NEAREST_MIPMAP_LINEAR);
// Rendered bigger than texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
width,
height,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
pixels
);
// Generate mipmaps
int mipmap_level = 0;
int offset = width * height * 4;
while(width > 1 && height > 1 && offset != pixels_len) {
// Divide width & height.
width >>= 1;
height >>= 1;
// Increase mipmap level.
mipmap_level += 1;
glTexImage2D(
GL_TEXTURE_2D,
mipmap_level,
GL_RGBA,
width,
height,
0,
GL_RGBA,
0x1401,
pixels + offset,
);
offset += width * height * 4;
}
glTexParameteri(
GL_TEXTURE_2D,
GL_TEXTURE_MAX_LEVEL,
mipmap_level,
);