Inverse-square light falloff

Bring the lamp close. Why can one sphere be brightly lit while its neighbour stays dark?
Interactive demo#LightAndGlow3D lighting
Doubling the distance to a point light leaves a facing surface with one quarter of the incident light.
Reconstruct the front of each sphere and measure the 3D distance from its surface to the lamp. Divide the intensity by distance squared, then multiply by how directly the surface faces the light. The final display curve compresses the brightest values.
Code
namespace light_attenuation_lesson;
import stage;
import std;
import math;
var pixels: u8[64000] = [0;64000];
export "light-attenuation" fn draw(time: f64, dt: f64, px: f64, py: f64, hover: bool) {
load_texture("studio");
let lamp_z = number_control("distance", 50);
let lamp_x = if hover { px } else { 78 + 50 * sin(time * 0.6) };
for y in 100 {
for x in 160 {
let n = sphere_surface(x, y);
if n.radius == 0 {
let backdrop = studio_colour(x, y);
put_rgb(pixels[..], x, y, backdrop[0], backdrop[1], backdrop[2]);
continue;
}
let dx = lamp_x - x;
let dy = y - 22;
let dz = lamp_z - n.nz * n.radius;
let distance2 = max(1.0, dx * dx + dy * dy + dz * dz);
let facing = max(0.0, (n.nx * dx + n.ny * dy + n.nz * dz) / sqrt(distance2));
let energy = 2200 * facing / distance2;
// Compress highlights for display.
let v = 0.08 + 0.92 * energy / (1 + energy);
let clay = if n.radius > 20 { [237.0, 182.0, 124.0] } else { [138.0, 191.0, 172.0] };
put_rgb(pixels[..], x, y, clay[0] * v, clay[1] * v, clay[2] * v);
}
}
pixel_buffer(pixels[..], 160, 100);
}

Comments
No comments yet.