Home > OS >  How does one pass an array with no fixed size into the vertex shader?
How does one pass an array with no fixed size into the vertex shader?

Time:01-25

I have an array with no fixed size (let noise = [];) in my .js file where it stores the noise values for a point (noise[i] -> a single point).

I was wondering if I'm able to pass all the values inside the array into my vertex.shader by doing:

//.js
for(let i = 0; i < noise.length; i  ) {
    const uNoise = gl.getUniformLocation(program, "uNoise["   i   "]");
    gl.uniform3fv(uNoise, MV.flatten(noise[i]));
}

//vertex.shader
let uNoise[];

If not, how would it possible to do it?

CodePudding user response:

The locations of uniforms aggregated into arrays are ascending. Therefore you can simply do:

const uNoise = gl.getUniformLocation(program, "uNoise");
gl.uniform1f(uNoise, new Float32Array(MV.flatten(noise)));

CodePudding user response:

It's not possible to have variable sized arrays as uniforms in shaders. What you could do is allocate an array of a fixed size that represents your maximum number of elements and then send an additional integer uniform with the actual element count.

uniform int numElements;
uniform float noise[1024];

The you can use this technique to iterate through the values(if you need to).

Another approach would be to put the values in a texture and sample from that, if this is really just noise then you'd probably want to have a simple noise texture that just wraps around to begin with as it's a lot more comfortable to work with in a shader, on that note another alternative is to use an isomorphic pseudo-random function that you can run on the CPU and GPU to receive the same output when you put in the same data.

  •  Tags:  
  • Related