Reputation: 452
I'm creating a program where I'm using the GPU to do computations (via fragment shaders) and need to store signed values inside textures.
My texture is initialized with GL_FLOAT, like so:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, nullptr);
And from what I understand about opengl, individual texels must be in the range [0,1] when GL_FLOAT is used (when I experimented with glClear, my values would be clipped to this range). So what I've been doing so far is scaling my values down to the range [-1,1] based on their actual range, then converting that to [0,1] before writing it back to the texture. The next shader that needs to work with the data reads the texel value and moves it to [-1,1] before continuing and so on...
My question is, is this the right way to deal with negative values? I'm pretty sure the repeated conversions are causing fp errors to accumulate which obviously isn't good for accuracy.
Thank you
Upvotes: 2
Views: 1654
Reputation: 5797
See also: Difference between format and internalformat
The internal format (third parameter of glTexImage2D
) decides how the GPU stores and interprets those values, not the type parameter of glTexImage2D
(second-to-last parameter). That parameter decides how the driver should interpret your client/host-side memory when uploading to the texture, which you currently don't use by using nullptr
.
You could use the signed 8-bit GL_RGBA8_SNORM
or the 16-bit floating point GL_RGBA16F
or 32-bit floating-point GL_RGBA32F
sized internal format for the texture.
Generally, you should always use a sized internal format to be explicit about what you want and get.
See the table on: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml
So, if you only need 8-bit resolution, and values in the range [-1, 1], then you can use:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8_SNORM, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
The second-to-last argument is actually irrelevant, because we are not uploading any texel data to the texture.
Upvotes: 1