Last time, we got the basic renderer up and running. Now we have more complex issues to deal with. For example, how to light the LOD models.

### Lighting

One approach to lighting is to simply light the detailed model, and bake that lighting into the LOD texture. This works, but requires that all lights be static. We can do better.

The standard shading equation has three parts: ambient light, diffuse light, and specular light:

(For details of how these equations work, see Wikipedia.)

The key thing to notice is that these equations rely only on the texture (which we already have), a unit direction towards the light source, a unit direction towards the camera, and the unit surface normal. By rendering our detailed model down to a texture, we’ve destroyed the normal data. But that’s easy enough to fix: we write it to a texture as well.

(Setup for this texture is more-or-less the same as the color texture, we just bind it to a different output.)

// Detail vertex shader
in vec3 position;
in vec3 normal;
out vec3 Normal;
void main() {
gl_Position = position;
Normal = normal;
}
// Detail fragment shader
in vec3 Normal;
out vec4 frag_color;
out vec4 normal_map_color;
void main() {
vec3 normal = (normalize(Normal) + vec3(1.0)) / 2.0;
frag_color = vec4(1.0);
normal_map_color = vec4(normal, 1.0);
}

A unit normal is simply a vector of 3 floats between -1 and 1. We can map this to a RGB color (vec3 clamped to [0, 1]) by adding one and dividing by two. This is, again, nothing new. You may be wondering why we store an alpha channel — we’ll get to that later.

We can now reconstruct the normal from the LOD texture. This is all we need for directional lights:

// Fragment shader
uniform sampler2D color_texture;
uniform sampler2D normal_map_texture;
uniform vec3 sun_direction;
uniform vec3 camera_direction;
in vec2 uv;
out vec4 frag_color;
void main() {
vec4 normal_sample = texture(normal_map_texture, uv);
vec3 normal = (normal.xyz * 2.0) - vec3(1.0);
vec3 view = -1.0 * camera_direction;
vec3 view_half = (normal + view) / length(normal + view);
float n_dot_l = dot(normal, sun_direction);
float n_dot_h = dot(normal, view_half);
float ambient_intensity = 0.25;
float diffuse_intensity = 0.5;
float specular_intensity = 0.0;
if (n_dot_l > 0) {
specular_intensity = 0.25 * pow(n_dot_h, 10);
}
vec4 texture_sample = texture(color_texture, uv);
vec3 lit_color = ambient_intensity * texture_sample.rgb +
diffuse_intensity * texture_sample.rgb +
specular_intensity * vec3(1.0);
frag_color = vec4(lit_color, texture_sample.a);
}

Result:

### Point / Spot Lighting

So this solves directional lights. However, point and spot lights have attenuation — they fall off over distance. Additionally, they have an actual spatial position, which means the light vector will change.

After rendering the LODs, we no longer have the vertex positions of our detail model. Calculating lighting based on the LOD model’s vertices will, in many cases, be obviously wrong. How can we reconstruct the original points?

By cheating.

Let’s look at what we have to work with:

The camera is orthographic, which means that depth of a pixel is independent of where it is on screen. We have the camera’s forward vector (camera_direction in the above shader).

Finally, and most obviously, we don’t care about shading the points that weren’t rendered to our LOD texture.

This turns out to be the important factor. If we knew how far each pixel was from the camera when rendered, we could reconstruct the original location for lighting.

To put it another way, we need a depth buffer. Remember that normal map alpha value we didn’t use?

We can get the depth value like so:

// Map depth from [near, far] to [-1, 1]
float depth = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) / (gl_DepthRange.far - gl_DepthRange.near);
// Remap normal and depth from [-1, 1] to [0, 1]
normal_depth_color = (vec4(normalize(normal_vec), depth) + vec4(1.0)) / 2.0;

However, we now run into a problem. This depth value is in the LOD render’s window space. We want the position in the final render’s camera space — this way we can transform the light position to the same space, which allows us to do the attenuation calculations.

There are a few ways to handle this. One is to record the depth range for our LOD model after rendering it, and then use that to scale the depth properly. This is complex (asymmetrical models can have different depth sizes for each rotation) and quite likely inconsistent, due to precision errors.

A simpler solution, then, is to pick an arbitrary depth range, and use it consistently for both the main render and LODs. This is not ideal — one getting out of sync with the other may lead to subtle errors. In a production design, it may be a good idea to record the camera matrix used in the model data, so that it can be confirmed on load.

We need two further pieces of data to proceed: the viewport coordinates (the size of the window) and the inverse projection matrix (to “unproject” the position back into camera space). Both of these are fairly trivial to provide. To reconstruct the proper position, then:

vec3 window_to_camera_space(vec3 window_space) {
// viewport = vec4(x, y, width, height)
// Because projection is orthographic, NDC == clip space
vec2 clip_xy = ((2.0 * window_space.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1.0;
// Already mapped to [-1, 1] by the same transform that extracts our normal.
float clip_z = window_space.z
vec4 clip_space = vec4(clip_xy, clip_z, 1.0);
vec4 camera_space = camera_from_clip * clip_space;
return camera_space.xyz;
}

(Note that this is rather inefficient. We *know* what a projection matrix looks like, so that last multiply can be made a lot faster.)

Calculating the light color is the same as for directional lights. For point lights, we then divide by an attenuation factor:

float attenuation = point_light_attenuation.x +
point_light_attenuation.y * light_distance +
point_light_attenuation.z * light_distance * light_distance;
point_light_color = point_light_color / attenuation;

This uses 3 factors: constant, linear, and quadratic. The constant factor determines the base intensity of the light (a fractional constant brightens the light, a constant greater than 1.0 darkens it.) The linear and quadratic factors control the fall-off curve.

A spot light has the same attenuation factors, but also has another term:

float spot_intensity = pow(max(dot(-1.0 * spot_direction, light_direction), 0.0), spot_exponent);

The dot product here limits the light to a cone around the spotlight’s facing direction. The exponential factor controls the “tightness” of the light cone — as the exponent increases, the fall-off becomes much sharper (remember that the dot product of unit vectors produces a value in [0, 1]).

So that covers lighting. Next time: exploring options for shadows.

**NOTE:**

I made some errors with terminology in my last post. After the projection transform is applied, vertices are in *clip* space, not eye space. The series of transforms is as follows:

Model -> World -> Camera -> Clip -> NDC

(With an orthographic projection, Clip == NDC.)