Build a path tracer from scratch over one weekend — no external libraries, no graphics API, just math, vectors, and a lot of randomly bouncing photons.
Hello, world — but in pixels.
Ray tracing is one of the most beautiful pieces of code you'll ever write. The whole program fits in a few hundred lines, has zero dependencies, and produces pictures that look almost photographic. The original book uses C++. We're using Go because it's the language many of you already work with, the syntax is friendly, and Go's standard library gives us everything we need — files, math, randomness — out of the box.
Here's the mental model: a ray tracer simulates how light travels. For every pixel on the screen, we shoot an imaginary ray from the camera into the scene and ask, "what colour does this ray see?" If it hits a sphere, we figure out the colour at that point. If it hits the sky, we use a sky colour. That's the whole game.
Create a new Go module. We'll keep everything in a single package main for simplicity — adding folder structure later only distracts from the math.
# Create the project
mkdir raytracer && cd raytracer
go mod init raytracer
# Folder structure we'll build
raytracer/
├── go.mod
├── main.go
├── vec3.go
├── ray.go
├── hittable.go
├── sphere.go
├── camera.go
└── material.go
Don't copy-paste blindly. Type the code in. The mistakes you make while typing teach you more than the lines that work the first time. Peter Shirley says this in the original book and he's right.
Before we render anything fancy, we need to output an image. The simplest format on Earth is PPM: a plain-text file where the first three lines describe the image, and every line after that is just three numbers — red, green, blue, each between 0 and 255.
P3 # magic number — "this is a plain-text PPM"
256 256 # width and height in pixels
255 # max colour value
0 0 0 # pixel (0,0): pure black
1 0 0 # pixel (1,0): tiniest bit of red
2 0 0
... and so on, left-to-right, top-to-bottom
That's it. Most image viewers on Linux and Mac can open PPM directly. On Windows, install IrfanView or use the online viewer ppmviewer.com. We'll write the file to standard output and redirect with >.
This program produces a gradient — red increases left-to-right, green increases top-to-bottom. The bottom-right corner will be yellow (red + green = yellow in additive light).
package main
import (
"fmt"
"os"
)
func main() {
// Image dimensions
const imageWidth, imageHeight = 256, 256
// PPM header
fmt.Printf("P3\n%d %d\n255\n", imageWidth, imageHeight)
// Render — top to bottom, left to right
for j := 0; j < imageHeight; j++ {
fmt.Fprintf(os.Stderr, "\rScanlines remaining: %d ", imageHeight-j)
for i := 0; i < imageWidth; i++ {
r := float64(i) / float64(imageWidth-1)
g := float64(j) / float64(imageHeight-1)
b := 0.0
ir := int(255.999 * r)
ig := int(255.999 * g)
ib := int(255.999 * b)
fmt.Printf("%d %d %d\n", ir, ig, ib)
}
}
fmt.Fprintln(os.Stderr, "\nDone.")
}
os.Stderr for the progress? Because we're writing the image to stdout. If the progress text also went to stdout, it would corrupt the file. Stderr shows up in the terminal but doesn't go into the redirected file.255.999 trick — multiplying by 255.999 instead of 255 ensures that when r is exactly 1.0 we get 255, not 256. Casting to int truncates.Red increases →, green increases ↓. Bottom-right corner: yellow.
If your viewer says "invalid PPM file," your shell may have written it as UTF-16. Use go run . > image.ppm in bash or zsh, not PowerShell. On Windows, run inside Git Bash or WSL.
One struct to rule positions, directions, and colours.
In 3D graphics, you constantly work with three different things that all happen to be triples of numbers:
The original book uses one C++ class vec3 for all three. We'll do the same in Go with a Vec3 struct. Yes, you could make separate types — and you'd get type safety — but you'd also write three times as many helper functions. We're optimizing for short code that you can keep in your head.
Go doesn't have operator overloading, so where C++ writes a + b we write a.Add(b). Slightly more typing, but unambiguous. Add this file to your project:
package main
import "math"
// Vec3 is a 3D vector. We use it for points, directions, AND colours.
type Vec3 struct {
X, Y, Z float64
}
// Aliases — no real type safety, but they help readability.
type Point3 = Vec3
type Color = Vec3
// Constructor
func NewVec3(x, y, z float64) Vec3 { return Vec3{x, y, z} }
// --- arithmetic ---
func (v Vec3) Add(u Vec3) Vec3 { return Vec3{v.X + u.X, v.Y + u.Y, v.Z + u.Z} }
func (v Vec3) Sub(u Vec3) Vec3 { return Vec3{v.X - u.X, v.Y - u.Y, v.Z - u.Z} }
func (v Vec3) Mul(u Vec3) Vec3 { return Vec3{v.X * u.X, v.Y * u.Y, v.Z * u.Z} }
func (v Vec3) Scale(t float64) Vec3 { return Vec3{v.X * t, v.Y * t, v.Z * t} }
func (v Vec3) Div(t float64) Vec3 { return v.Scale(1 / t) }
func (v Vec3) Neg() Vec3 { return Vec3{-v.X, -v.Y, -v.Z} }
// --- length / dot / cross ---
func (v Vec3) LengthSquared() float64 { return v.X*v.X + v.Y*v.Y + v.Z*v.Z }
func (v Vec3) Length() float64 { return math.Sqrt(v.LengthSquared()) }
func Dot(a, b Vec3) float64 {
return a.X*b.X + a.Y*b.Y + a.Z*b.Z
}
func Cross(a, b Vec3) Vec3 {
return Vec3{
a.Y*b.Z - a.Z*b.Y,
a.Z*b.X - a.X*b.Z,
a.X*b.Y - a.Y*b.X,
}
}
func (v Vec3) Unit() Vec3 { return v.Div(v.Length()) }
Move the "convert (r,g,b) ∈ [0,1] to bytes ∈ [0,255]" logic into its own helper. We'll extend it later to handle multiple samples and gamma correction.
// WriteColor outputs a single pixel's colour in PPM byte format.
func (c Color) WriteColor(w io.Writer) {
ir := int(255.999 * c.X)
ig := int(255.999 * c.Y)
ib := int(255.999 * c.Z)
fmt.Fprintf(w, "%d %d %d\n", ir, ig, ib)
}
Don't forget to import "io" and "fmt" at the top of vec3.go.
func main() {
const imageWidth, imageHeight = 256, 256
fmt.Printf("P3\n%d %d\n255\n", imageWidth, imageHeight)
for j := 0; j < imageHeight; j++ {
fmt.Fprintf(os.Stderr, "\rScanlines remaining: %d ", imageHeight-j)
for i := 0; i < imageWidth; i++ {
pixel := NewVec3(
float64(i)/float64(imageWidth-1),
float64(j)/float64(imageHeight-1),
0,
)
pixel.WriteColor(os.Stdout)
}
}
fmt.Fprintln(os.Stderr, "\nDone.")
}
Same gradient as before, but now we have the toolkit for everything that follows.
Send a ray through every pixel. Paint the sky.
A ray is just a half-line: an origin point plus a direction. We parametrise it with a number t:
P(t) = A + t · b
Plug in t = 0, you're at the origin A. Plug in t = 1, you're one step along direction b. Bigger t → further along the ray. That's all.
package main
type Ray struct {
Origin Point3
Direction Vec3
}
func (r Ray) At(t float64) Point3 {
return r.Origin.Add(r.Direction.Scale(t))
}
Imagine a virtual rectangle floating in front of the camera. Every pixel of our image corresponds to a tiny square on that rectangle. We shoot a ray from the camera (the "eye") through the centre of each pixel-square and into the world. Whatever colour the ray "sees" becomes the pixel's colour.
The book uses a 16:9 aspect ratio and a viewport height of 2.0 units (in arbitrary "world space"). Our coordinate system:
Pixel coordinates have Y going down (top-left is (0,0)). World coordinates have Y going up. We bridge the two with a "viewport_v" vector that points downward in world space — that's why it'll have a negative Y component.
For now, every ray we shoot will miss everything (no objects exist yet) and hit the "sky." We compute the sky colour from the ray's direction: rays pointing up are blue, rays pointing forward/down are white. This is just a lerp (linear interpolation):
colour = (1 − a) · white + a · blue
where a goes from 0 at the bottom to 1 at the top.
package main
import (
"fmt"
"os"
)
func rayColor(r Ray) Color {
unitDir := r.Direction.Unit()
a := 0.5 * (unitDir.Y + 1.0) // remap Y from [-1,1] to [0,1]
white := NewVec3(1.0, 1.0, 1.0)
blue := NewVec3(0.5, 0.7, 1.0)
return white.Scale(1.0-a).Add(blue.Scale(a))
}
func main() {
// Image
const aspectRatio = 16.0 / 9.0
imageWidth := 400
imageHeight := int(float64(imageWidth) / aspectRatio)
if imageHeight < 1 { imageHeight = 1 }
// Camera
focalLength := 1.0
viewportHeight := 2.0
viewportWidth := viewportHeight * float64(imageWidth) / float64(imageHeight)
cameraCenter := NewVec3(0, 0, 0)
// Vectors across the viewport edges
viewportU := NewVec3(viewportWidth, 0, 0)
viewportV := NewVec3(0, -viewportHeight, 0) // negative — Y is flipped
// Per-pixel deltas
pixelDeltaU := viewportU.Div(float64(imageWidth))
pixelDeltaV := viewportV.Div(float64(imageHeight))
// Top-left pixel location
viewportUL := cameraCenter.
Sub(NewVec3(0, 0, focalLength)).
Sub(viewportU.Div(2)).
Sub(viewportV.Div(2))
pixel00 := viewportUL.Add(pixelDeltaU.Add(pixelDeltaV).Scale(0.5))
// Render
fmt.Printf("P3\n%d %d\n255\n", imageWidth, imageHeight)
for j := 0; j < imageHeight; j++ {
fmt.Fprintf(os.Stderr, "\rScanlines remaining: %d ", imageHeight-j)
for i := 0; i < imageWidth; i++ {
pixelCenter := pixel00.
Add(pixelDeltaU.Scale(float64(i))).
Add(pixelDeltaV.Scale(float64(j)))
rayDir := pixelCenter.Sub(cameraCenter)
r := Ray{Origin: cameraCenter, Direction: rayDir}
rayColor(r).WriteColor(os.Stdout)
}
}
fmt.Fprintln(os.Stderr, "\nDone.")
}
For every pixel (i, j), we compute its position in world space by starting at pixel00 (the centre of the top-left pixel) and stepping i times right and j times down. We then shoot a ray from the camera at (0,0,0) through that point. Since there are no objects yet, every ray "hits the sky" — and we colour it based on how steeply it points up.
Top: blue-ish (0.5, 0.7, 1.0). Bottom: pure white. Aspect ratio 16:9.
A red dot in the sky. From algebra, no less.
Because the math for "does this ray hit this sphere?" is very simple compared to other shapes. A sphere of radius r centred at point C is the set of points P where:
(C − P) · (C − P) = r²
That dot product is just the squared distance. So the equation says: "if your distance from C is r, you're on the sphere." Simple.
Our ray is P(t) = Q + t·d (the book uses Q for origin and d for direction). We want to find the t values where P(t) lies on the sphere. Substitute and grind through the algebra and you get a quadratic equation in t:
t² (d·d) − 2t · d·(C−Q) + (C−Q)·(C−Q) − r² = 0
Quadratic = use the quadratic formula. Three cases for the discriminant b² − 4ac:
This is the heart of every ray tracer. Once you can detect "ray hits sphere," you can detect "ray hits anything" — triangles, cubes, fractals, all use the same pattern: "given a ray, find the closest t where it intersects me, or report a miss."
// hitSphere returns true if ray r hits a sphere of radius `radius` centred at `center`.
func hitSphere(center Point3, radius float64, r Ray) bool {
oc := center.Sub(r.Origin) // C - Q
a := Dot(r.Direction, r.Direction)
b := -2.0 * Dot(r.Direction, oc)
c := Dot(oc, oc) - radius*radius
discriminant := b*b - 4*a*c
return discriminant >= 0
}
func rayColor(r Ray) Color {
if hitSphere(NewVec3(0, 0, -1), 0.5, r) {
return NewVec3(1, 0, 0) // red
}
unitDir := r.Direction.Unit()
a := 0.5 * (unitDir.Y + 1.0)
return NewVec3(1, 1, 1).Scale(1.0-a).
Add(NewVec3(0.5, 0.7, 1.0).Scale(a))
}
We're placing a sphere of radius 0.5 at (0, 0, −1) — directly in front of the camera, one unit away.
It looks 2D because we're not yet shading — every hit pixel gets the same red.
Our hit test returns true for negative t too — meaning the sphere also gets coloured red if it's behind the camera. We'll fix this in the next module when we start caring about which intersection point we hit.
Three-dimensional shading. Multiple objects. Clean architecture.
A normal is a unit vector pointing straight out of a surface at a particular point. On a sphere, the normal at any point is just the direction from the centre to that point — like how on Earth, "up" always points away from the planet's centre.
To see our sphere as 3D, we'll do a classic trick: visualise the normal as a colour. Map the (x, y, z) of the normal — each in [−1, 1] — to (r, g, b) in [0, 1]. Suddenly the sphere has different colours on different sides, and we can perceive its shape.
Until now hitSphere returned bool. Now we want it to return t — the parameter value at the closest intersection — so we can compute the hit point.
// Returns the smaller t value where the ray hits the sphere, or -1 if it misses.
func hitSphere(center Point3, radius float64, r Ray) float64 {
oc := center.Sub(r.Origin)
a := r.Direction.LengthSquared() // d·d == |d|²
h := Dot(r.Direction, oc) // simplified — see book
c := oc.LengthSquared() - radius*radius
discriminant := h*h - a*c
if discriminant < 0 {
return -1.0
}
return (h - math.Sqrt(discriminant)) / a // closer of the two roots
}
func rayColor(r Ray) Color {
t := hitSphere(NewVec3(0, 0, -1), 0.5, r)
if t > 0 {
N := r.At(t).Sub(NewVec3(0, 0, -1)).Unit()
return NewVec3(N.X+1, N.Y+1, N.Z+1).Scale(0.5)
}
unitDir := r.Direction.Unit()
a := 0.5 * (unitDir.Y + 1.0)
return NewVec3(1, 1, 1).Scale(1.0-a).
Add(NewVec3(0.5, 0.7, 1.0).Scale(a))
}
You'll need to import "math" in main.go. Run it — the sphere now has shaded colours: red on the right, green on top, blue near the camera. That's the normals visualisation.
Each pixel is coloured by which way the surface faces. The sphere finally looks 3D.
Right now we hard-code one sphere. Let's design properly: any object that a ray can hit will satisfy a Hittable interface. We'll have a Sphere type, and a HittableList that itself is hittable (it just delegates to its children).
package main
// HitRecord captures everything we want to know about a ray-surface intersection.
type HitRecord struct {
P Point3 // hit point
Normal Vec3 // surface normal at hit point (unit length)
T float64 // ray parameter at hit
FrontFace bool // true if ray hit the outside of the surface
Mat Material // added in module 7 — leave nil for now
}
// SetFaceNormal makes Normal point against the incoming ray.
func (rec *HitRecord) SetFaceNormal(r Ray, outwardNormal Vec3) {
rec.FrontFace = Dot(r.Direction, outwardNormal) < 0
if rec.FrontFace {
rec.Normal = outwardNormal
} else {
rec.Normal = outwardNormal.Neg()
}
}
// Hittable is anything a ray can intersect.
type Hittable interface {
Hit(r Ray, tMin, tMax float64, rec *HitRecord) bool
}
// HittableList itself satisfies Hittable.
type HittableList struct {
Objects []Hittable
}
func (hl *HittableList) Add(o Hittable) { hl.Objects = append(hl.Objects, o) }
func (hl HittableList) Hit(r Ray, tMin, tMax float64, rec *HitRecord) bool {
var tempRec HitRecord
hitAnything := false
closest := tMax
for _, obj := range hl.Objects {
if obj.Hit(r, tMin, closest, &tempRec) {
hitAnything = true
closest = tempRec.T
*rec = tempRec
}
}
return hitAnything
}
Why a Material field on HitRecord? We'll add real materials in module 7. For now, leave Material as an undefined symbol — we'll create the type stub now so the code compiles.
package main
// Material — full definition comes in module 7. Stub for now.
type Material interface {
Scatter(rIn Ray, rec *HitRecord) (attenuation Color, scattered Ray, ok bool)
}
package main
import "math"
type Sphere struct {
Center Point3
Radius float64
Mat Material
}
func (s Sphere) Hit(r Ray, tMin, tMax float64, rec *HitRecord) bool {
oc := s.Center.Sub(r.Origin)
a := r.Direction.LengthSquared()
h := Dot(r.Direction, oc)
c := oc.LengthSquared() - s.Radius*s.Radius
discriminant := h*h - a*c
if discriminant < 0 {
return false
}
sqrtd := math.Sqrt(discriminant)
// Find the nearest t in (tMin, tMax)
root := (h - sqrtd) / a
if root <= tMin || tMax <= root {
root = (h + sqrtd) / a
if root <= tMin || tMax <= root {
return false
}
}
rec.T = root
rec.P = r.At(root)
outwardNormal := rec.P.Sub(s.Center).Div(s.Radius)
rec.SetFaceNormal(r, outwardNormal)
rec.Mat = s.Mat
return true
}
func rayColor(r Ray, world Hittable) Color {
var rec HitRecord
if world.Hit(r, 0, math.MaxFloat64, &rec) {
return rec.Normal.Add(NewVec3(1, 1, 1)).Scale(0.5)
}
unitDir := r.Direction.Unit()
a := 0.5 * (unitDir.Y + 1.0)
return NewVec3(1, 1, 1).Scale(1.0-a).
Add(NewVec3(0.5, 0.7, 1.0).Scale(a))
}
func main() {
// World
var world HittableList
world.Add(Sphere{Center: NewVec3(0, 0, -1), Radius: 0.5})
world.Add(Sphere{Center: NewVec3(0, -100.5, -1), Radius: 100}) // the "ground"
// ... rest of main is the same as module 3,
// just call rayColor(r, world) instead of rayColor(r) ...
}
The trick of using a giant sphere as the ground — radius 100, centred 100.5 below the visible sphere — is a classic. Its top surface, where it meets the visible scene, looks essentially flat from the camera's perspective.
Two spheres rendered through one Hittable interface. Now we're an actual ray tracer.
vec3.go, ray.go, hittable.go, sphere.go, material.go, main.go.Smooth edges. Cleaner architecture.
Right now main does too much. We'll move all the rendering logic into a Camera type. main will only build the world and configure the camera. This pays off massively in module 9 when we add a positionable camera.
We pass tMin, tMax everywhere. Group them into a single Interval type — small thing, but cleans up signatures.
package main
import "math"
type Interval struct {
Min, Max float64
}
var EmptyInterval = Interval{math.Inf(1), math.Inf(-1)}
var UniverseInterval = Interval{math.Inf(-1), math.Inf(1)}
func (i Interval) Contains(x float64) bool { return i.Min <= x && x <= i.Max }
func (i Interval) Surrounds(x float64) bool { return i.Min < x && x < i.Max }
func (i Interval) Clamp(x float64) float64 {
if x < i.Min { return i.Min }
if x > i.Max { return i.Max }
return x
}
Update Hittable and Sphere to take an Interval instead of two floats:
type Hittable interface {
Hit(r Ray, rayT Interval, rec *HitRecord) bool
}
func (hl HittableList) Hit(r Ray, rayT Interval, rec *HitRecord) bool {
var tempRec HitRecord
hitAnything := false
closest := rayT.Max
for _, obj := range hl.Objects {
if obj.Hit(r, Interval{rayT.Min, closest}, &tempRec) {
hitAnything = true
closest = tempRec.T
*rec = tempRec
}
}
return hitAnything
}
And in sphere.go, replace tMin, tMax float64 with rayT Interval and use rayT.Surrounds(root) in the bounds checks.
If you zoom into our last image, the edges look like staircases. That's aliasing: each pixel is sampled at exactly one point (its centre), so it's either fully sphere or fully sky. Real cameras and real eyes don't work that way — edge pixels are a mix of foreground and background, depending on what proportion of the pixel area each occupies.
The fix: shoot many rays per pixel, each through a slightly different random point inside the pixel's square, and average the results. With 100 samples per pixel, edges become naturally smooth.
package main
import (
"fmt"
"math"
"math/rand"
"os"
)
type Camera struct {
AspectRatio float64 // e.g. 16/9
ImageWidth int
SamplesPerPixel int
MaxDepth int // max bounces — used in module 6
// computed by initialize()
imageHeight int
pixelSamples float64
center Point3
pixel00 Point3
pixelDeltaU Vec3
pixelDeltaV Vec3
}
func (c *Camera) initialize() {
c.imageHeight = int(float64(c.ImageWidth) / c.AspectRatio)
if c.imageHeight < 1 { c.imageHeight = 1 }
c.pixelSamples = 1.0 / float64(c.SamplesPerPixel)
c.center = NewVec3(0, 0, 0)
focalLength := 1.0
viewportHeight := 2.0
viewportWidth := viewportHeight * float64(c.ImageWidth) / float64(c.imageHeight)
viewportU := NewVec3(viewportWidth, 0, 0)
viewportV := NewVec3(0, -viewportHeight, 0)
c.pixelDeltaU = viewportU.Div(float64(c.ImageWidth))
c.pixelDeltaV = viewportV.Div(float64(c.imageHeight))
viewportUL := c.center.
Sub(NewVec3(0, 0, focalLength)).
Sub(viewportU.Div(2)).
Sub(viewportV.Div(2))
c.pixel00 = viewportUL.Add(c.pixelDeltaU.Add(c.pixelDeltaV).Scale(0.5))
}
// getRay returns a ray for pixel (i, j) with a random sub-pixel offset.
func (c *Camera) getRay(i, j int) Ray {
offsetX := rand.Float64() - 0.5
offsetY := rand.Float64() - 0.5
pixelSample := c.pixel00.
Add(c.pixelDeltaU.Scale(float64(i) + offsetX)).
Add(c.pixelDeltaV.Scale(float64(j) + offsetY))
return Ray{Origin: c.center, Direction: pixelSample.Sub(c.center)}
}
// rayColor — kept simple for now; we'll evolve this in module 6.
func (c *Camera) rayColor(r Ray, world Hittable) Color {
var rec HitRecord
if world.Hit(r, Interval{0, math.MaxFloat64}, &rec) {
return rec.Normal.Add(NewVec3(1, 1, 1)).Scale(0.5)
}
unitDir := r.Direction.Unit()
a := 0.5 * (unitDir.Y + 1.0)
return NewVec3(1, 1, 1).Scale(1.0-a).
Add(NewVec3(0.5, 0.7, 1.0).Scale(a))
}
func (c *Camera) Render(world Hittable) {
c.initialize()
fmt.Printf("P3\n%d %d\n255\n", c.ImageWidth, c.imageHeight)
for j := 0; j < c.imageHeight; j++ {
fmt.Fprintf(os.Stderr, "\rScanlines remaining: %d ", c.imageHeight-j)
for i := 0; i < c.ImageWidth; i++ {
pixel := NewVec3(0, 0, 0)
for s := 0; s < c.SamplesPerPixel; s++ {
r := c.getRay(i, j)
pixel = pixel.Add(c.rayColor(r, world))
}
pixel.Scale(c.pixelSamples).WriteColor(os.Stdout)
}
}
fmt.Fprintln(os.Stderr, "\nDone.")
}
WriteColor with clampingBecause we're now averaging colours, a value can occasionally exceed [0, 1] due to floating-point oddities. Clamp it:
func (c Color) WriteColor(w io.Writer) {
intensity := Interval{0.000, 0.999}
ir := int(256 * intensity.Clamp(c.X))
ig := int(256 * intensity.Clamp(c.Y))
ib := int(256 * intensity.Clamp(c.Z))
fmt.Fprintf(w, "%d %d %d\n", ir, ig, ib)
}
func main() {
var world HittableList
world.Add(Sphere{Center: NewVec3(0, 0, -1), Radius: 0.5})
world.Add(Sphere{Center: NewVec3(0, -100.5, -1), Radius: 100})
cam := Camera{
AspectRatio: 16.0 / 9.0,
ImageWidth: 400,
SamplesPerPixel: 100,
MaxDepth: 50,
}
cam.Render(world)
}
Notice the rendering is now noticeably slower (100× more rays). Edges should be visibly smoother — soft transitions instead of staircase steps.
Always run go build -o rt . && ./rt > img.ppm instead of go run for renders that take more than a few seconds. go run rebuilds every time and adds startup overhead.
Light, scattered randomly, becomes shadow.
A diffuse (or matte) surface scatters incoming light in random directions. Think of unfinished wood, plaster, fabric. When light hits it, some of the light is absorbed (depending on colour) and the rest bounces off in some random direction.
So when our ray hits a diffuse surface, instead of immediately returning a colour, we:
That's recursion — and it's the heart of path tracing. Light bounces and bounces and bounces until it eventually escapes to the sky (or gets absorbed). The colour you see is the result of all those bounces.
We need a way to generate a random direction. The trick is the rejection method: generate a random point inside the cube [-1, 1]³, throw it away if it's outside the unit sphere (or pathologically close to zero), and otherwise normalize it.
import "math/rand"
func RandomVec3() Vec3 {
return Vec3{rand.Float64(), rand.Float64(), rand.Float64()}
}
func RandomVec3Range(min, max float64) Vec3 {
return Vec3{
min + (max-min)*rand.Float64(),
min + (max-min)*rand.Float64(),
min + (max-min)*rand.Float64(),
}
}
func RandomUnitVector() Vec3 {
for {
p := RandomVec3Range(-1, 1)
lensq := p.LengthSquared()
if 1e-160 < lensq && lensq <= 1 {
return p.Div(math.Sqrt(lensq))
}
}
}
// NearZero — used by metal reflections to detect degenerate scatter directions.
func (v Vec3) NearZero() bool {
const s = 1e-8
return math.Abs(v.X) < s && math.Abs(v.Y) < s && math.Abs(v.Z) < s
}
Instead of scattering uniformly in any direction "above" the surface (which is a valid but cruder model), we use the Lambertian distribution: scatter direction = surface normal + random unit vector. This biases scatter toward the normal, which matches how real matte surfaces behave (the angles closer to "straight up off the surface" are more probable).
scatter_direction = N + random_unit_vector()
Recursion needs a base case. Without one, a ray might bounce around forever and overflow the stack. We add depth — when it hits zero, return black (no more light).
func (c *Camera) rayColor(r Ray, depth int, world Hittable) Color {
if depth <= 0 {
return NewVec3(0, 0, 0)
}
var rec HitRecord
// tMin = 0.001 to avoid "shadow acne" — see callout below
if world.Hit(r, Interval{0.001, math.MaxFloat64}, &rec) {
direction := rec.Normal.Add(RandomUnitVector())
return c.rayColor(Ray{rec.P, direction}, depth-1, world).Scale(0.5)
}
unitDir := r.Direction.Unit()
a := 0.5 * (unitDir.Y + 1.0)
return NewVec3(1, 1, 1).Scale(1.0-a).
Add(NewVec3(0.5, 0.7, 1.0).Scale(a))
}
Don't forget to update the call in Render to pass c.MaxDepth:
pixel = pixel.Add(c.rayColor(r, c.MaxDepth, world))
Why tMin = 0.001 and not 0? Because of floating-point imprecision, the new ray's origin might be just below the surface it bounced off of, and immediately re-hit it at t ≈ 0.0000001. Result: speckled black dots all over the spheres. The 0.001 tolerance ignores those bogus near-zero hits.
The render now looks dark and dingy. Real screens display colour with a non-linear curve (sRGB). To compensate, we raise each colour component to the power 1/γ where γ ≈ 2 — easiest done with a square root:
func linearToGamma(c float64) float64 {
if c > 0 { return math.Sqrt(c) }
return 0
}
func (c Color) WriteColor(w io.Writer) {
r := linearToGamma(c.X)
g := linearToGamma(c.Y)
b := linearToGamma(c.Z)
intensity := Interval{0.000, 0.999}
fmt.Fprintf(w, "%d %d %d\n",
int(256*intensity.Clamp(r)),
int(256*intensity.Clamp(g)),
int(256*intensity.Clamp(b)),
)
}
The image now looks bright, with realistic soft shadows underneath the sphere. This is path tracing. The shadow exists because rays bouncing in those directions hit the bottom of the sphere instead of the bright sky.
Soft shadow underneath. Sky tint visible on the top of the sphere.
Mirrors, polished steel, and rays that don't pick directions at random.
So far the "material" was hard-coded into rayColor: every hit produced a half-strength scattered ray. That's not flexible. Let's give every surface a material that decides:
package main
import "math"
type Material interface {
Scatter(rIn Ray, rec *HitRecord) (attenuation Color, scattered Ray, ok bool)
}
// --- Lambertian (diffuse) ---
type Lambertian struct {
Albedo Color
}
func (l Lambertian) Scatter(rIn Ray, rec *HitRecord) (Color, Ray, bool) {
dir := rec.Normal.Add(RandomUnitVector())
// Catch degenerate cases where dir cancels out
if dir.NearZero() {
dir = rec.Normal
}
return l.Albedo, Ray{rec.P, dir}, true
}
// --- Metal ---
type Metal struct {
Albedo Color
Fuzz float64 // 0 = mirror, 1 = very rough
}
func Reflect(v, n Vec3) Vec3 {
return v.Sub(n.Scale(2 * Dot(v, n)))
}
func (m Metal) Scatter(rIn Ray, rec *HitRecord) (Color, Ray, bool) {
reflected := Reflect(rIn.Direction.Unit(), rec.Normal)
fuzz := math.Min(m.Fuzz, 1)
reflected = reflected.Add(RandomUnitVector().Scale(fuzz))
scattered := Ray{rec.P, reflected}
ok := Dot(scattered.Direction, rec.Normal) > 0
return m.Albedo, scattered, ok
}
When a ray hits a mirror, it bounces off at the same angle on the other side of the normal — like a billiard ball off a cushion. The formula v − 2(v·n)n says: take the incoming direction, subtract twice its component along the normal. The result is the reflected direction.
For fuzzy metal (brushed steel, less than perfect mirrors), we add a tiny random vector to the reflected direction. Bigger fuzz = blurrier reflection.
func (c *Camera) rayColor(r Ray, depth int, world Hittable) Color {
if depth <= 0 {
return NewVec3(0, 0, 0)
}
var rec HitRecord
if world.Hit(r, Interval{0.001, math.MaxFloat64}, &rec) {
attenuation, scattered, ok := rec.Mat.Scatter(r, &rec)
if ok {
return attenuation.Mul(c.rayColor(scattered, depth-1, world))
}
return NewVec3(0, 0, 0)
}
unitDir := r.Direction.Unit()
a := 0.5 * (unitDir.Y + 1.0)
return NewVec3(1, 1, 1).Scale(1.0-a).
Add(NewVec3(0.5, 0.7, 1.0).Scale(a))
}
func main() {
matGround := Lambertian{Albedo: NewVec3(0.8, 0.8, 0.0)} // yellowish
matCenter := Lambertian{Albedo: NewVec3(0.1, 0.2, 0.5)} // blue matte
matLeft := Metal{Albedo: NewVec3(0.8, 0.8, 0.8), Fuzz: 0.0} // mirror
matRight := Metal{Albedo: NewVec3(0.8, 0.6, 0.2), Fuzz: 0.5} // fuzzy gold
var world HittableList
world.Add(Sphere{Center: NewVec3(0, -100.5, -1), Radius: 100, Mat: matGround})
world.Add(Sphere{Center: NewVec3(0, 0, -1.2), Radius: 0.5, Mat: matCenter})
world.Add(Sphere{Center: NewVec3(-1, 0, -1), Radius: 0.5, Mat: matLeft})
world.Add(Sphere{Center: NewVec3(1, 0, -1), Radius: 0.5, Mat: matRight})
cam := Camera{
AspectRatio: 16.0 / 9.0,
ImageWidth: 400,
SamplesPerPixel: 100,
MaxDepth: 50,
}
cam.Render(world)
}
The mirror sphere reflects the world. Notice the rough sphere has a slightly blurry reflection.
When light bends. Snell, Schlick, and total internal reflection.
Glass, water, diamonds — clear materials that refract light (bend it as it enters and exits) instead of reflecting it. The amount of bending depends on the refractive index (η, "eta"): air ≈ 1.0, water ≈ 1.33, glass ≈ 1.5, diamond ≈ 2.4.
When light crosses from medium A (refractive index ηA) into medium B (ηB), the angle changes according to:
ηA · sin(θA) = ηB · sin(θB)
If the new medium is denser, the ray bends toward the normal. If it's less dense, the ray bends away. And in some cases — when leaving glass at a steep angle — the equation has no solution, and the ray can't refract at all. That's total internal reflection, which is why glass spheres have those bright spots.
The Schlick approximation tells us how the probability of reflection (vs refraction) varies with the viewing angle. At grazing angles, even glass reflects most of the light — that's why a calm pond is mirror-like when you look across it.
// Refract returns the refracted ray direction given an incoming unit vector,
// the surface normal, and the ratio etaIn / etaOut.
func Refract(uv, n Vec3, etaiOverEtat float64) Vec3 {
cosTheta := math.Min(Dot(uv.Neg(), n), 1.0)
rOutPerp := uv.Add(n.Scale(cosTheta)).Scale(etaiOverEtat)
rOutParallel := n.Scale(-math.Sqrt(math.Abs(1.0 - rOutPerp.LengthSquared())))
return rOutPerp.Add(rOutParallel)
}
import "math/rand"
type Dielectric struct {
RefractionIndex float64
}
func schlick(cosine, refIdx float64) float64 {
r0 := (1 - refIdx) / (1 + refIdx)
r0 = r0 * r0
return r0 + (1-r0)*math.Pow(1-cosine, 5)
}
func (d Dielectric) Scatter(rIn Ray, rec *HitRecord) (Color, Ray, bool) {
attenuation := NewVec3(1, 1, 1) // glass doesn't absorb light
ri := d.RefractionIndex
if rec.FrontFace {
ri = 1.0 / d.RefractionIndex
}
unitDir := rIn.Direction.Unit()
cosTheta := math.Min(Dot(unitDir.Neg(), rec.Normal), 1.0)
sinTheta := math.Sqrt(1.0 - cosTheta*cosTheta)
cannotRefract := ri*sinTheta > 1.0
var direction Vec3
if cannotRefract || schlick(cosTheta, ri) > rand.Float64() {
direction = Reflect(unitDir, rec.Normal)
} else {
direction = Refract(unitDir, rec.Normal, ri)
}
return attenuation, Ray{rec.P, direction}, true
}
A glass sphere with a slightly smaller glass sphere of negative radius inside it gives you a hollow glass shell — like a glass marble. Negative radius doesn't change the geometry, but it inverts the surface normal, so the inside of the outer sphere acts like the inside of a soap bubble.
matCenter := Dielectric{RefractionIndex: 1.50} // glass
matBubble := Dielectric{RefractionIndex: 1.00 / 1.50} // air pocket inside
world.Add(Sphere{Center: NewVec3(0, 0, -1.2), Radius: 0.5, Mat: matCenter})
world.Add(Sphere{Center: NewVec3(0, 0, -1.2), Radius: 0.4, Mat: matBubble})
Wait — but our Sphere uses radius for normalisation and would crash on negative radius. The book handles this by using fmax(0, radius) in the constructor. We can adopt a different convention: keep radius positive but flip the normal in the scatter logic. The simpler approach: use the trick from the book — make the inner sphere a smaller positive-radius dielectric with the inverted refractive index.
The glass sphere shows refraction — the world behind it appears flipped and bent.
Look from anywhere. Look at anything.
From these, we compute three orthogonal unit vectors that form the camera's local coordinate system:
type Camera struct {
AspectRatio float64
ImageWidth int
SamplesPerPixel int
MaxDepth int
VFov float64 // vertical field of view, degrees
LookFrom Point3
LookAt Point3
VUp Vec3
// computed
imageHeight int
pixelSamples float64
center Point3
pixel00 Point3
pixelDeltaU Vec3
pixelDeltaV Vec3
}
func (c *Camera) initialize() {
c.imageHeight = int(float64(c.ImageWidth) / c.AspectRatio)
if c.imageHeight < 1 { c.imageHeight = 1 }
c.pixelSamples = 1.0 / float64(c.SamplesPerPixel)
c.center = c.LookFrom
focalLength := c.LookFrom.Sub(c.LookAt).Length()
theta := c.VFov * math.Pi / 180.0
h := math.Tan(theta / 2)
viewportHeight := 2 * h * focalLength
viewportWidth := viewportHeight * float64(c.ImageWidth) / float64(c.imageHeight)
w := c.LookFrom.Sub(c.LookAt).Unit()
u := Cross(c.VUp, w).Unit()
v := Cross(w, u)
viewportU := u.Scale(viewportWidth)
viewportV := v.Neg().Scale(viewportHeight)
c.pixelDeltaU = viewportU.Div(float64(c.ImageWidth))
c.pixelDeltaV = viewportV.Div(float64(c.imageHeight))
viewportUL := c.center.
Sub(w.Scale(focalLength)).
Sub(viewportU.Div(2)).
Sub(viewportV.Div(2))
c.pixel00 = viewportUL.Add(c.pixelDeltaU.Add(c.pixelDeltaV).Scale(0.5))
}
Now you can configure the camera anywhere:
cam := Camera{
AspectRatio: 16.0 / 9.0,
ImageWidth: 400,
SamplesPerPixel: 100,
MaxDepth: 50,
VFov: 20,
LookFrom: NewVec3(-2, 2, 1),
LookAt: NewVec3(0, 0, -1),
VUp: NewVec3(0, 1, 0),
}
You're now looking at the scene from above and to the left. Try different values to get a feel for the controls.
Depth of field. The cinematic effect.
Real cameras have lenses with finite size. Light from a point at the focus distance converges to a single pixel — sharp. Light from any other distance lands as a small disk — blur. The bigger the lens (or aperture), the more dramatic the blur.
To simulate it, instead of shooting every ray from a single camera point, we shoot from a random point on a small disk centred at the camera. All these rays still aim at the same pixel target on the focus plane, so points exactly at that distance always look the same — but other points get a slightly different ray each sample, producing blur.
func RandomInUnitDisk() Vec3 {
for {
p := Vec3{rand.Float64()*2 - 1, rand.Float64()*2 - 1, 0}
if p.LengthSquared() < 1 {
return p
}
}
}
type Camera struct {
// ... previous fields ...
DefocusAngle float64 // in degrees, 0 = no blur
FocusDist float64 // distance to plane of perfect focus
// computed
defocusDiskU Vec3
defocusDiskV Vec3
}
In initialize, replace focalLength := lookFrom.Sub(lookAt).Length() with the explicit focus distance, and add at the end:
defocusRadius := c.FocusDist * math.Tan((c.DefocusAngle/2) * math.Pi / 180)
c.defocusDiskU = u.Scale(defocusRadius)
c.defocusDiskV = v.Scale(defocusRadius)
And update getRay:
func (c *Camera) getRay(i, j int) Ray {
offsetX := rand.Float64() - 0.5
offsetY := rand.Float64() - 0.5
pixelSample := c.pixel00.
Add(c.pixelDeltaU.Scale(float64(i) + offsetX)).
Add(c.pixelDeltaV.Scale(float64(j) + offsetY))
var origin Point3
if c.DefocusAngle <= 0 {
origin = c.center
} else {
p := RandomInUnitDisk()
origin = c.center.
Add(c.defocusDiskU.Scale(p.X)).
Add(c.defocusDiskV.Scale(p.Y))
}
return Ray{Origin: origin, Direction: pixelSample.Sub(origin)}
}
Set DefocusAngle to about 0.6 and FocusDist to 3.4 in main, and you'll see crisp spheres at that distance with soft, blurred backgrounds.
Hundreds of spheres. The cover image.
Three big spheres (one glass, one matte brown, one polished metal) on a vast diffuse ground, surrounded by hundreds of small randomly-placed, randomly-coloured, randomly-material spheres. This is what the whole book has been building to.
func randomScene() HittableList {
var world HittableList
ground := Lambertian{Albedo: NewVec3(0.5, 0.5, 0.5)}
world.Add(Sphere{Center: NewVec3(0, -1000, 0), Radius: 1000, Mat: ground})
for a := -11; a < 11; a++ {
for b := -11; b < 11; b++ {
chooseMat := rand.Float64()
center := NewVec3(
float64(a) + 0.9*rand.Float64(),
0.2,
float64(b) + 0.9*rand.Float64(),
)
if center.Sub(NewVec3(4, 0.2, 0)).Length() <= 0.9 {
continue
}
var mat Material
switch {
case chooseMat < 0.8: // diffuse
albedo := RandomVec3().Mul(RandomVec3())
mat = Lambertian{Albedo: albedo}
case chooseMat < 0.95: // metal
albedo := RandomVec3Range(0.5, 1)
fuzz := rand.Float64() * 0.5
mat = Metal{Albedo: albedo, Fuzz: fuzz}
default: // glass
mat = Dielectric{RefractionIndex: 1.5}
}
world.Add(Sphere{Center: center, Radius: 0.2, Mat: mat})
}
}
world.Add(Sphere{Center: NewVec3(0, 1, 0), Radius: 1.0, Mat: Dielectric{RefractionIndex: 1.5}})
world.Add(Sphere{Center: NewVec3(-4, 1, 0), Radius: 1.0, Mat: Lambertian{Albedo: NewVec3(0.4, 0.2, 0.1)}})
world.Add(Sphere{Center: NewVec3(4, 1, 0), Radius: 1.0, Mat: Metal{Albedo: NewVec3(0.7, 0.6, 0.5), Fuzz: 0.0}})
return world
}
func main() {
world := randomScene()
cam := Camera{
AspectRatio: 16.0 / 9.0,
ImageWidth: 1200,
SamplesPerPixel: 500,
MaxDepth: 50,
VFov: 20,
LookFrom: NewVec3(13, 2, 3),
LookAt: NewVec3(0, 0, 0),
VUp: NewVec3(0, 1, 0),
DefocusAngle: 0.6,
FocusDist: 10.0,
}
cam.Render(world)
}
This render at 1200×675 with 500 samples per pixel is slow. Hours, on a single core. Go's goroutines make parallelisation embarrassingly easy. Add this to Render:
import "runtime"
import "sync"
func (c *Camera) Render(world Hittable) {
c.initialize()
// Allocate the full pixel buffer up front
pixels := make([]Color, c.ImageWidth*c.imageHeight)
var wg sync.WaitGroup
workers := runtime.NumCPU()
rowsPerWorker := (c.imageHeight + workers - 1) / workers
var done atomic.Int64
for w := 0; w < workers; w++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
startJ := workerID * rowsPerWorker
endJ := startJ + rowsPerWorker
if endJ > c.imageHeight {
endJ = c.imageHeight
}
for j := startJ; j < endJ; j++ {
for i := 0; i < c.ImageWidth; i++ {
pixel := NewVec3(0, 0, 0)
for s := 0; s < c.SamplesPerPixel; s++ {
r := c.getRay(i, j)
pixel = pixel.Add(c.rayColor(r, c.MaxDepth, world))
}
pixels[j*c.ImageWidth+i] = pixel.Scale(c.pixelSamples)
}
d := done.Add(1)
fmt.Fprintf(os.Stderr, "\rRendered %d / %d rows ", d, int64(c.imageHeight))
}
}(w)
}
wg.Wait()
// Write the assembled image
fmt.Printf("P3\n%d %d\n255\n", c.ImageWidth, c.imageHeight)
for _, p := range pixels {
p.WriteColor(os.Stdout)
}
fmt.Fprintln(os.Stderr, "\nDone.")
}
Add "sync/atomic" to your imports. On an 8-core machine, this gives you roughly a 6–7× speedup. Note: math/rand is goroutine-safe in modern Go, but for absolute reproducibility you'd want each worker to have its own *rand.Rand instance.
Convert PPM to PNG with ImageMagick: convert final.ppm final.png. Or use a viewer that handles PPM directly.
| Concept | Lines of Go |
|---|---|
| Vec3 + helpers | ~100 |
| Ray + Hittable + Sphere | ~80 |
| Camera with antialiasing & defocus | ~120 |
| Lambertian + Metal + Dielectric | ~80 |
| Interval + Color helpers | ~30 |
| main + scene | ~50 |
| Total | ~460 lines |
Peter Shirley, Trevor David Black, and Steve Hollasch wrote Ray Tracing in One Weekend and gave it away for free. If this workshop landed for you, give them a star on the RayTracing GitHub repo and tell other people about the books. They are some of the best free programming material on the web.