0
votes

Edit: Removed alot of clutter and rephrased the question.

I have stored an array of floats into my shader using:

float simpleArray2D[4] = { 10.0f, 20.0f, 30.0f, 400.0f };
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 2, 2, 0, GL_RGB, GL_FLOAT, &simpleArray2D);

How do I access specific elements from the float array in the shader?

Specific fragment shader code showing what I've done to test it so far, displaying a green color when the value is the specified one (10.0f in this case), and red if it's not.

vec2 textureCoordinates = vec2(0.0f, 0.0f);
float testValueFloat = float(texture(floatArraySampler, textureCoordinates));
outColor = testValueFloat >= 10.0f ? vec4(0,1,0,1) : vec4(1,0,0,1); //Showed green
//outColor = testValueFloat >= 10.1f ? vec4(0,1,0,1) : vec4(1,0,0,1); //Showed red
1
What is the specific reason to use a texture for this? You may be better off with using an UBO, TBO or SSBO.derhass
It's for loading an array of about 700 floats into the GPU, and I'm accessing different parts of the array depending on tessellation coordinatessprux
In this case, you would be much better off by using an UBO or SSBO.derhass
I will look into it. Would I typically always use UBO or SSBO when storing +100 floats into a shader? If I measure the execution time per frame on a static scene comparing the methods, would I be able to notice a difference?sprux
What you will measure will depend on a lot of different factors, but an UBO is the right place for getting a few kB of data to the shaders, and will allow the GL implementation to chose the optimal path on the actual hardware.derhass

1 Answers

1
votes

In GLSL you can use texelFetch to get a texel from a texture by integral coordinates.
This means the texels of the texture can be addressed similar the elements of an array, by its index:

ivec2 ij = ivec2(0, 0);
float testValueFloat = texelFetch(floatArraySampler, ij, 0).r;

But note, the array consists of 4 elements.

float simpleArray2D[4] = { 10.0f, 20.0f, 30.0f, 400.0f };

So the texture can be a 2x2 texture with one color channel (GL_RED)

glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 2, 2, 0, GL_RED, GL_FLOAT, &simpleArray2D);

or a 1x1 texture with 4 color channels (GL_RGBA)

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 1, 1, 0, GL_RGBA, GL_FLOAT, &simpleArray2D);

but it can't be a 2x2 RGBA texture, because for this the array would have to have 16 elements.