0

I would like to apply multiples lights in my shader. To do that, I've make the choice to put lights data in multiple arrays instead of one light = one struct to avoid doing "setUniforms" a lot of time.

I've got something like that:

// Light's data.
struct LightData 
{
   vec3 ambient[4];
   vec3 diffuse[4];
   vec3 position[4];
   vec3 specular[4];
};
uniform LightData lights;


vec3 applyLight( int index, vec3 cameraPos )
{
    vec3 position = lights.position[index]; //<<< Error here.
    …
    return result;
}

int main()
{
    vec3 color;

    for( int i = 0; i < 4; i++)
        color += applyLight(i, camera.position);
}

The problem is in the GLSL code: "index expression must be constant []". How can I do to have this code to work? I could give position, diffuse, ambient, specular to the function but it will by dirty.

What about performances? It is better to have something like what I've done or like the code bellow?

struct Light 
{
   vec3 ambient;
   vec3 diffuse;
   vec3 position;
   vec3 specular;
};
uniform Light lights[4];

Have a nice day!

1

1 Answer 1

2

Unroll your loop:

color += applyLight(0, camera.position);
color += applyLight(1, camera.position);
color += applyLight(2, camera.position);
color += applyLight(3, camera.position);

(not sure if this exact code will work, but you get the idea)

lights.position[index]; // no
lights.position[0]; // yes, etc

Option below (for uniform layout) might be better, it may have a better locality.

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

2 Comments

Thanks but "4" is for the exemple, I would like to manage less or more lights with another integer (lights.lightCount)
if(7<lightCount) { color+=lambert(light[7], normal); } something like should do the trick.

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.