0

I wondering how I am supposed to loop through an array from a shader. I've read a lot of things but I'm still quite confused.

Here is the JavaScript that creates the array:

var particles = []; // I'm creating an array of x and y coordinates
for (var i = 0; i < 100; i++) {
    particles.push([
            Math.floor(Math.random()*1000) + .5, 
            Math.floor(Math.random()*1000) + .5
        ]);
}
gl.uniform2fv(gl.getUniformLocation(glProgram, 'particles'), particles);

And here is a piece of my fragment shader:

uniform vec2 particles;

void main( void ) {
    bool found = false;
    for (int i = 0; i < 100; i ++) {
        if (particles[i].x == 1.0) {
            found = true;
        }
    }
}

The error I'm getting is "field selection requires structure or vector on left hand side". What am I missing?

4
  • Don't know much about WebGL, but I would guess your declaration of particles in your shader is incorrect, it should probably be uniform vec2 particles[100];. Commented Jan 3, 2018 at 14:34
  • Well you're right. You just saved me a lot of time, thanks! Commented Jan 3, 2018 at 14:42
  • FYI: Of course do whatever you want but it's not common to use large arrays of uniforms given that the min max size is 128. Meaning if you declare uniform vec2 particles[129] where will be many GPUs that can't run the shader because they support a maximum array size of 128. (currently 1 of 4 will fail) Typically if you need random access to data you put that data in a texture. Commented Jan 4, 2018 at 3:36
  • Passing by this question, but without additional context your code gives me the sense that you might want to re-organize your data so you know which points have a .x of 1.0 before the shader steps. You could create separate buffers. That way you could avoid the linear search. Commented Feb 9, 2018 at 1:23

1 Answer 1

1

The declaration of particles in the shader was incorrect, it defined a single vec2 rather than an array of vec2.

The right declaration is:

uniform vec2 particles[100];
Sign up to request clarification or add additional context in comments.

Comments

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.