user569322
user569322

Reputation:

GLSL - Trying to add multiple lights?

I have a simple fragment shader that simulates 2D lighting, like so:

struct Light
{
    vec2 pos;     // Light position
    float spread;    // Light spread
    float size;   // Light bulb size
};

void main(void)
{
    Light light0;    // Define the light
    light0.pos = iMouse.xy;    // Set the position to mouse coords
    light0.spread = 500.0;
    light0.size = 200.0;

    float x_dis = light0.pos.x - gl_FragCoord.x;   
    float y_dis = light0.pos.y - gl_FragCoord.y;

    float intensity = sqrt(pow(x_dis, 2.0) + pow(y_dis, 2.0))-light0.size;  // Pythagorean Theorem - size
    if(intensity < 0.0)
        intensity = 0.0;
    else
        intensity /= light0.spread;    // Divide the intensity by the spread

    gl_FragColor = vec4(1.0-intensity, 1.0-intensity, 1.0-intensity, 1.0);
}

That puts one light on the screen. (You can view it here https://www.shadertoy.com/view/XsX3Wl)

I thought, "Hey, that was pretty easy! I'll just make a for loop and combine the light intensities!"

So that's what I did:

struct Light
{
    vec2 pos;     // Light position
    float spread;    // Light spread
    float size;   // Light bulb size
};

void main(void)
{
    Light lights[2];

    Light light0;
    light0.pos = iMouse.xy;
    light0.spread = 500.0;
    light0.size = 200.0;

    Light light1;
    light0.pos = iMouse.xy;
    light0.spread = 500.0;
    light0.size = 200.0;

    float intensity = 0.0;
    for(int i = 0; i < 2; i++)
    {
        float x_dis = lights[i].pos.x - gl_FragCoord.x;   
        float y_dis = lights[i].pos.y - gl_FragCoord.y;

        float sub_ints = sqrt(pow(x_dis, 2.0) + pow(y_dis, 2.0))-lights[i].size;  // Intensity relative to this light
        if(sub_ints < 0.0)
            sub_ints = 0.0;

        sub_ints /= lights[i].spread;    // Divide the intensity by the spread

        intensity += sub_ints;
    }

    gl_FragColor = vec4(1.0-intensity, 1.0-intensity, 1.0-intensity, 1.0);
}

You can see by https://www.shadertoy.com/view/4dX3Wl that this doesn't work. But I'm confused? How would I accumulate the intensities of the lights on a particular pixel?

Upvotes: 0

Views: 583

Answers (1)

Marius
Marius

Reputation: 2273

Light light1;
light0.pos = iMouse.xy;
light0.spread = 500.0;
light0.size = 200.0;

You are not initializing light1 here. Maybe spread is zero and you produce a NaN when dividing by it.

I know copy&paste errors happen but that one was easy to spot. You should do a serious review of your code before posting it on SO.

Upvotes: 2

Related Questions