Skip to the content ForoHackers
Log inJoin

A ray tracer in 40 lines: what the key lines are doing

Computer graphicsPuzzlesRendering
#1056 · quiet_quine · · Report

Most tiny ray tracers are the same program: for each pixel, shoot a ray, find the nearest sphere, shade it. The heart is ray-sphere intersection, which is just a quadratic.

A ray is origin + t * direction. A sphere is every point at distance radius from center. Substitute one into the other and you get a t² + b t + c = 0:

from math import sqrt

def hit_sphere(center, radius, origin, direction):
    oc = [o - c for o, c in zip(origin, center)]
    a = sum(d * d for d in direction)
    b = 2.0 * sum(o * d for o, d in zip(oc, direction))
    c = sum(o * o for o in oc) - radius * radius
    disc = b * b - 4 * a * c
    if disc < 0:
        return None              # the ray misses
    t = (-b - sqrt(disc)) / (2 * a)
    return t if t > 1e-4 else None

Negative discriminant: miss. Otherwise take the nearer root, and ignore hits behind the camera or glued to the origin (that 1e-4).

Shading: normal is (p - center) / radius, brightness is max(0, dot(normal, to_light)). That is Lambert. Everything else (shadows, reflections) is recursion on the same function.

#1594 · undefined_behaviour_enjoyer · · Report

The 1e-4 is the part people skip, and then they get "shadow acne": the secondary ray starts on the surface, floating point says it is slightly inside, and the sphere shadows itself in speckles. A fixed epsilon works for a toy; for real scenes you offset along the normal or scale the epsilon with the magnitude of the hit point.

#1595 · r3l1c_0f_bbs · · Report

I wrote one of these in BASIC as a teenager. It took the whole night to render one blurry sphere, and I thought it was the most beautiful thing I had ever seen. Leaving it running and going to sleep was the original "batch job".

#1596 · quiet_quine · · Report

Shadow acne is the correct name. Mine fixed itself by accident the first time: wrong sign, no sphere ever visible.

#1597 · packet_loss_poet · · Report

Ray tracing in three lines:

One quadratic asks whether light meets the sphere: square root, or empty sky.

Log in or join to reply.