0

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
7
  • What is the specific reason to use a texture for this? You may be better off with using an UBO, TBO or SSBO. Commented Feb 15, 2019 at 20:39
  • 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 coordinates Commented Feb 27, 2019 at 2:17
  • In this case, you would be much better off by using an UBO or SSBO. Commented Feb 27, 2019 at 18:48
  • 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? Commented Mar 4, 2019 at 3:12
  • 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. Commented Mar 4, 2019 at 19:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the information you provided helped me solve it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.