我有一个模拟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看到这不起作用。但我很困惑?如何在特定像素上累积光的强度?
答案 0 :(得分:2)
Light light1;
light0.pos = iMouse.xy;
light0.spread = 500.0;
light0.size = 200.0;
你没有在这里初始化light1。也许传播是零,你在除以它时会产生一个NaN。
我知道发生了复制和粘贴错误,但很容易发现错误。在将代码发布到SO之前,您应该仔细检查代码。