0

我有一个模拟 2D 光照的简单片段着色器,如下所示:

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);
}

这会在屏幕上放一盏灯。(您可以在这里查看https://www.shadertoy.com/view/XsX3Wl

我想,“嘿,这很容易!我将只创建一个 for 循环并结合光强度!”

所以这就是我所做的:

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);
}

您可以通过https://www.shadertoy.com/view/4dX3Wl看到这不起作用。但我很困惑?我将如何累积特定像素上的灯光强度?

4

1 回答 1

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

您没有在这里初始化 light1。也许价差为零,除以它时会产生 NaN。

我知道会发生复制和粘贴错误,但很容易发现。在将代码发布到 SO 之前,您应该认真审查您的代码。

于 2013-10-08T19:12:25.440 回答