OpenGL - Sparse Textures

If you work with OpenGL (like me) you sometimes find it hard to get some more modern examples of code. I recently was looking around for an example of ARB_bindless_texture and never really found it. And because I managed to write one I will share it: 


GLuint hwTexture;
GLint patchSize = 1024;   // Size of single patch
GLint pageSizesCount = 1; // Number of page sizes to choose from 
GLint pageSizeX = 0, pageSizeY = 0, pageSizeZ = 0; // Size of page.

// Create texture and mark it as sparse
glCreateTextures(GL_TEXTURE_2D, 1, &hwTexture);
glTextureParameteri(hwTexture, GL_TEXTURE_SPARSE_ARB, GL_TRUE);

// Get numbers of available VIRTUAL_PAGE_SIZE_... 
glGetInternalformativ(GL_TEXTURE_2D, GL_RGBA8, GL_NUM_VIRTUAL_PAGE_SIZES_ARB, 1, &pageSizesCount);

// For simplicity of example I get here only the first one.  
glGetInternalformativ(GL_TEXTURE_2D, GL_RGBA8, GL_VIRTUAL_PAGE_SIZE_X_ARB, 1, &pageSizeX);
glGetInternalformativ(GL_TEXTURE_2D, GL_RGBA8, GL_VIRTUAL_PAGE_SIZE_Y_ARB, 1, &pageSizeY);
glGetInternalformativ(GL_TEXTURE_2D, GL_RGBA8, GL_VIRTUAL_PAGE_SIZE_Z_ARB, 1, &pageSizeZ);

// Select page size 0 (there may be more than one)
glTextureParameteri(hwTexture, GL_VIRTUAL_PAGE_SIZE_INDEX_ARB, 0);

// Allocate space for the sparse texture (it does not have at this point any backing memory).
glTextureStorage2D(hwTexture, 1, GL_RGBA8, 
patchSize*pageSizeX, patchSize*pageSizeY);

// Commit memory and fill it with data
glTexturePageCommitmentEXT(hwTexture, 0, 0, 0, 0, size, size, 1, true);
std::vector<uint32_t> memory(size*size, 0xFF0000FF);
glTextureSubImage2D(hwTexture, 0, 0, 0, 
patchSizepatchSize, GL_RGBA, GL_UNSIGNED_BYTE, memory.data()));

//Here, you can use this texture as any other image
....

// Uncommiting memory 
glTexturePageCommitmentEXT(hwTexture, 0, 0, 0, 0, size, size, 1, true); 



Maybe one day this will help someone :]

Sources:














Comments

Popular posts from this blog

Query commands execution

W.U. 0x21

WRE