sfml lighting in csharp

To implement lighting in SFML, we can use shaders. Here is a basic implementation of a point light:

main.cs
Shader pointLightShader = new Shader(null, null, "pointLight.frag");

pointLightShader.SetParameter("texture", sfmlTexture);
pointLightShader.SetParameter("lightPosition", lightPosition);
pointLightShader.SetParameter("lightColor", lightColor);
pointLightShader.SetParameter("lightRadius", lightRadius);

// draw the sprite or geometry with the shader
352 chars
9 lines

In this example, we create a Shader object with a fragment shader file named "pointLight.frag". We then set several parameters on the shader including the texture to apply the lighting to, the position of the light, the color of the light, and the radius of the light.

The fragment shader file would contain the following code:

uniform sampler2D texture;
uniform vec2 lightPosition;
uniform vec3 lightColor;
uniform float lightRadius;

void main()
{
    vec4 texel = texture2D(texture, gl_TexCoord[0].xy);
    float distance = length(gl_TexCoord[0].xy - lightPosition);

    if (distance > lightRadius)
    {
        gl_FragColor = texel;
    }
    else
    {
        float attenuation = 1.0 - distance / lightRadius;
        gl_FragColor = vec4(texel.rgb * attenuation * lightColor, texel.a);
    }
}
474 chars
21 lines

This shader calculates the distance between the current pixel and the light position, and uses the distance to calculate an attenuation value. This attenuation is then used to darken the pixel color based on the distance to the light.

There are many ways to implement lighting in SFML, but this is one basic approach using shaders.

gistlibby LogSnag