I want to transfer a lot of images loaded by stb_image
to fragment shader by texture buffer object in OpenGL.
I first merge all the image data (every image file is in RGB format), and use one unsigned char
pointer named data
to point to them, this means all image data are put together in the format of RGBRGB...
Then, I used the following code to send all image data to fragment shader:
unsigned tbo, tex;
glGenBuffers(1, &tbo);
glBindBuffer(GL_TEXTURE_BUFFER, tbo);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_BUFFER, tex);
glTexBuffer(GL_TEXTURE_BUFFER, GL_R8UI, tbo);
glBindTexture(GL_TEXTURE_BUFFER, 0);
[...]
glBindBuffer(GL_TEXTURE_BUFFER, tbo);
glBufferData(GL_TEXTURE_BUFFER, len * sizeof(unsigned char),
NULL, GL_DYNAMIC_DRAW); // len is the length of data
glBufferSubData(GL_TEXTURE_BUFFER, 0, len * sizeof(unsigned char), data);
and in rendering loop:
shader.use();
glBindBuffer(GL_TEXTURE_BUFFER, tbo);
glBindTexture(GL_TEXTURE_BUFFER, tex);
[...]
in my fragment shader:
layout (binding = 0) uniform samplerBuffer image_texture_buffer;
out vec4 FragColor;
[...]
void main(){
FragColor = texelFetch(image_texture_buffer, 0);
}
[...]
But FragColor is always black.
Edited on 2021/4/3: I used this function to merge all the image data:
void merge_data(unsigned char *res, int lena, unsigned char *data, int lenb) {
//cout << lena << ' ' << lenb << endl;
res = (unsigned char *)realloc(res, lena + lenb);
//strcat_s((char *)res, sizeof data, (char *)data);
for (int i = lena, j = 0; j < lenb; ++i, ++j) res[i] = data[j];
}
In addition, someone told me that the video memory data must be aligned with even numbers, which means that I must transmit the data to the shader in the format of RGBARGBA...
, Is this the effect?