WebGL: passing uniform arrays to shader
Asked Answered
M

2

13

Tried to do just like here: Pass array to shader And like here: Passing an array of vectors to a uniform

But still no luck. I think I do just like there but it doesn't work:

Here's my JavaScript code:

shaderProgram.lightsUniform = gl.getUniformLocation(shaderProgram, "lights"); // Getting location
gl.uniform1f(shaderProgram.lightsUniform, new Float32Array([3,1,2,3,4,5])); // Let's try to send some light (currently each light is one float) as array.

Vertex Shader Code:

uniform float lights[6]; // Declaration

...

vLight *= lights[0]; // Let's try to mutliply our light by the first array item. There should be 3.0.

Summary: I send an array to shader with non-zero-floats.

Result: totally black! I.e. lights[0] contains 0.0 but expected 3.0. If I try lights[1], lights[2] etc. they all give the same result!

Let's now try to pass just one float. I change

gl.uniform1f(shaderProgram.lightsUniform, new Float32Array([3,1,2,3,4,5])); 

to

gl.uniform1f(shaderProgram.lightsUniform, 3); // I want to send just float 3.0

Summary: instead of sending array I send just float 3.0.

Result: works! lights[0] contains 3.0 (but I sent just float, not an array).

What do I do wrong? How do I pass to shader array of uniforms?

Mukerji answered 26/7, 2013 at 0:1 Comment(0)
G
10

Those answers all use the function uniform3fv. v as in vector.

So you should be using uniform1fv, not uniform1f for arrays of uniforms.

Gravamen answered 26/7, 2013 at 0:27 Comment(2)
I experienced a similar issue. But when I changed to uniform1fv, I got the following console error: Failed to execute 'uniform1fv' on 'WebGLRenderingContext': No function was found that matched the signature provided.Polyhistor
"check your OpenGL errors before asking questions" This is an inherently challenging space and can be incredibly overwhelming. This is well formed question, with a helpful and direct answer, which is the point of StackOverflow. There's no reason to tell someone they shouldn't ask a question.Bryna
P
-3

1: Make sure your if statement is within a function.

2: Make sure precision is set before declaring uniforms.

      #ifdef GL_FRAGMENT_PRECISION_HIGH
        precision highp float;
      #else
        precision mediump float;
      #endif
      precision mediump int;

3: Make sure comparison is of correct type:

This will FAIL:

uniform vec3 neon_whatever;
if(neon_whatever.x == 0){

};

This will FAIL:

uniform vec3 neon_whatever;
if(neon_whatever == 0.0){

};

This will WORK:

uniform vec3 neon_whatever;
if(neon_whatever.x == 0.0){

};
Pedigree answered 30/11, 2017 at 1:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.