Why a pumpkin?

This October I started Ray Tracing in One Weekend. I work in Unity and Unreal every day, so I’ve always had a GPU and an engine between me and the pixels. This book throws all of that away and asks: what if you computed every pixel yourself?

A few weeks in, I had a shaded sphere working. Then I wanted something fun to finish the month, so I turned it into a glowing jack-o’-lantern with a bloom effect.

I understood the code only halfway, so I’m rebuilding it from an empty project and writing up what I learn. The series has three parts:

  1. A window, a vector, and a purple sky (this post). Project setup, a minimal vec3 and ray, and a gradient sky.
  2. Hitting a sphere. Ray–sphere intersection, surface normals, simple lighting, and carving a face using the normal.
  3. Making it glow. An emissive mask, a separable Gaussian blur, and additive bloom.

Each part ends with an image you can run and see, plus exercises for practising from scratch.

The full source code is on GitHub: celebrate-season-with-raytracer.

Setup: Visual Studio + SDL2

The book writes images to .ppm files. That works, but every change means re-running the program, redirecting the output, and reopening the file in an image viewer. I switched to an SDL2 window so the result shows up as soon as the render finishes.

  1. In Visual Studio, create an Empty Project (C++). It starts with no generated files, so every line in the project is one you wrote.
  2. Set the language standard to C++17 or later for All Configurations: Project Properties → General → C++ Language Standard. We need this for std::clamp.
  3. Install SDL2 with a standalone vcpkg. The copy bundled with Visual Studio only supports manifest mode, so install your own. (Please look below for codes to run.) Restart Visual Studio afterwards. After that, #include <SDL2/SDL.h> works in every project, and SDL2.dll is copied next to your .exe automatically.
  4. Switch the build configuration to Release. In Part 3, the blur takes seconds in Debug and almost no time in Release.
git clone https://github.com/microsoft/vcpkg C:\vcpkg 

C:\vcpkg\bootstrap-vcpkg.bat 

C:\vcpkg\vcpkg install sdl2:x64-windows 

C:\vcpkg\vcpkg integrate install

The project has four files:

  • vec3.h: a 3D vector, used for points, directions, and colours
  • ray.h: a ray, which is an origin plus a direction
  • display.h: opens a window and shows a finished image
  • main.cpp: the camera and the rendering loop

One design choice matters later. The renderer first writes every pixel into a std::vector<vec3>, and only then hands the finished buffer to the window. Keeping “compute the image” separate from “show the image” is what makes the bloom in Part 3 easy to add.

vec3: only what we need

The book’s vec3 has about 30 operators and helpers. My first version copied all of them, and I couldn’t explain half. This time I’m starting with only what the pumpkin uses and adding more when I actually need it.

#pragma once
#include <cmath>

class vec3 {
public:
    float e[3];

    // The book's version leaves e[] uninitialised, so a vec3 you forgot to set holds random garbage. 
    // Starting from zero costs nothing and prevents a whole class of strange-looking bugs.
    vec3() : e{ 0.0f, 0.0f, 0.0f } {}
    vec3(float x, float y, float z) : e{ x, y, z } {}

    // Same data, two vocabularies: position or colour.
    float x() const { return e[0]; }
    float y() const { return e[1]; }
    float z() const { return e[2]; }
    float r() const { return e[0]; }
    float g() const { return e[1]; }
    float b() const { return e[2]; }

    vec3& operator+=(const vec3& v) {
        e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2];
        return *this;
    }

    float length() const {
        return std::sqrt(e[0] * e[0] + e[1] * e[1] + e[2] * e[2]);
    }
};

// Without inline, each file gets its own copy of operator+, and the linker fails with "already defined".
// const vec3& avoids copying.It passes a read, only reference instead of a copy. 
// For 12 bytes the speed difference is tiny, but it's the C++ habit I see everywhere in engine code.

inline vec3 operator+(const vec3& a, const vec3& b) {
    return vec3(a.e[0] + b.e[0], a.e[1] + b.e[1], a.e[2] + b.e[2]);
}

inline vec3 operator-(const vec3& a, const vec3& b) {
    return vec3(a.e[0] - b.e[0], a.e[1] - b.e[1], a.e[2] - b.e[2]);
}

// t * v and v * t are two separate functions. 
// C++ doesn't assume multiplication works both ways, so I define one and have the other call it.
inline vec3 operator*(float t, const vec3& v) {
    return vec3(t * v.e[0], t * v.e[1], t * v.e[2]);
}

inline vec3 operator*(const vec3& v, float t) { return t * v; }

inline vec3 operator/(const vec3& v, float t) { return (1.0f / t) * v; }

inline float dot(const vec3& a, const vec3& b) {
    return a.e[0] * b.e[0] + a.e[1] * b.e[1] + a.e[2] * b.e[2];
}

// For unit vectors, it gives 1 when they point the same way, 
// 0 when they're perpendicular, and −1 when they're opposite.
inline vec3 unit_vector(const vec3& v) { return v / v.length(); }

What I learned while rewriting it:

  • The default constructor sets everything to zero. The book’s version leaves e[] uninitialised, so a vec3 you forgot to set holds random garbage. Starting from zero costs nothing and prevents a whole class of strange-looking bugs.
  • inline on free functions is required, not a speed hint. This header gets included from several files. Without inline, each file gets its own copy of operator+, and the linker fails with “already defined”.
  • const vec3& avoids copying. It passes a read-only reference instead of a copy. For 12 bytes the speed difference is tiny, but it’s the C++ habit I see everywhere in engine code.
  • t * v and v * t are two separate functions. C++ doesn’t assume multiplication works both ways, so I define one and have the other call it.
  • dot isn’t used until Part 2. It’s included here because it’s the most important function in the file. For unit vectors, it gives 1 when they point the same way, 0 when they’re perpendicular, and −1 when they’re opposite.

ray: a point that moves along a line

A ray is a start point plus a direction. Any point along the ray can be found from a single number, t:

P(t)=A+tb→P(t) = A + t\,\vec{b}

Here A is the origin, b is the direction, t = 0 is the starting point, and larger values of t move further along the ray. Ray tracing mostly comes down to finding the t where a ray hits something. In Part 2, that t comes from solving a quadratic equation.

// ray.h
#pragma once
#include "vec3.h"

class ray {
public:
    ray() {}
    ray(const vec3& origin, const vec3& direction)
        : orig(origin), dir(direction) {
    }

    vec3 origin() const { return orig; }
    vec3 direction() const { return dir; }

    // The point at distance t along the ray.
    vec3 at(float t) const { return orig + t * dir; }

private:
    vec3 orig;
    vec3 dir;
};

The older edition of the book calls these A, B, and point_at_parameter(). The current online edition uses at(), which reads better, so I switched to it.

Camera and a purple Halloween sky

Showing the image

This function takes a finished image buffer, converts each colour from 0–1 floats to 8-bit values, uploads the result to the GPU as a texture, and keeps the window open until you close it. Drawing pixels one at a time with SDL_RenderDrawPoint also works, but uploading one texture is much faster and simpler.

#pragma once

// SDL_MAIN_HANDLED tells SDL not to replace your main() with its own entry point. 
// Without it, Visual Studio gives a linker error about SDL_main.
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#include <algorithm>
#include <cstdint>
#include <vector>
#include "vec3.h"

// 0..1 float -> 0..255 byte (values outside 0..1 are clamped)
inline uint32_t to_byte(float c) {
    return uint32_t(255.99f * std::clamp(c, 0.0f, 1.0f));
}

inline void show_image(const char* title,
    const std::vector<vec3>& image,
    int width, int height)
{
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow(title,
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        width, height, 0);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1,
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    SDL_Texture* texture = SDL_CreateTexture(renderer,
        SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC,
        width, height);

    // Pack each pixel into 0xAARRGGBB.
    std::vector<uint32_t> pixels(width * height);
    for (int i = 0; i < width * height; i++) {
        pixels[i] = (255u << 24)
            | (to_byte(image[i].r()) << 16)
            | (to_byte(image[i].g()) << 8)
            | to_byte(image[i].b());
    }
    SDL_UpdateTexture(texture, nullptr, pixels.data(),
        width * sizeof(uint32_t));

    bool running = true;
    while (running) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) running = false;
        }
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, nullptr, nullptr);
        SDL_RenderPresent(renderer);
    }

    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

SDL_MAIN_HANDLED tells SDL not to replace your main() with its own entry point. Without it, Visual Studio gives a linker error about SDL_main.

The camera

The eye sits at the origin, looking down −z. One unit in front of it is a 4 × 3 rectangle, the viewport. For each pixel, we find the matching point on the viewport and shoot a ray from the eye through it.

  • u goes from 0 to 1, left to right across the viewport.
  • v goes from 0 to 1, bottom to top.
  • Screen rows count downward, so we flip y with height - 1 - y. If you skip this, the image comes out upside down.
  • A 4 × 3 viewport on an 800 × 600 window keeps pixels square. If the two ratios don’t match, the sphere in Part 2 will look stretched.

The sky

The sky is a blend between two colours based on how far up the ray points. The y component of a unit direction runs from −1 (straight down) to +1 (straight up). Remapping it to 0–1 gives the blend factor t:

t = 0.5 · (dir.y + 1), color = (1 − t) · horizon + t · night

This is a lerp, the same as Mathf.Lerp in Unity or FMath::Lerp in Unreal. The book blends white to blue for a daytime sky. I chose magenta at the horizon and deep violet overhead.

#include <vector>
#include "vec3.h"
#include "ray.h"
#include "display.h"

vec3 sky_color(const ray& r)
{
vec3 dir = unit_vector(r.direction());


float t = 0.5f * (dir.y() + 1.0f);

vec3 horizon(0.60f, 0.15f, 0.48f); // magenta
vec3 night(0.09f, 0.03f, 0.22f); // deep violet

return (1.0f - t) * horizon + t * night;
}

int main()
{
const int width = 800;
const int height = 600;

// Camera
vec3 origin (0.0f, 0.0f, 0.0f);
vec3 lower_left (-2.0f, -1.5f, -1.0f);
vec3 horizontal(4.0f, 0.0f, 0.0f);
vec3 vertical(0.0f, 3.0f, 0.0f);

// Render into a buffer first, show it afterwords
std::vector<vec3> image(width * height);

for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float u = float(x) / float(width - 1);
float v = float(height - 1 - y) / float(height - 1);

vec3 direction = lower_left + u * horizontal + v * vertical - origin;
ray r(origin, direction);

image[y * width + x] = sky_color(r);
}

show_image("Halloween Ray Tracer - Part1", image, width, height);
return 0;
}

This is a lerp, the same as Mathf.Lerp in Unity or FMath::Lerp in Unreal. The book blends white to blue for a daytime sky. I chose magenta at the horizon and deep violet overhead.

y * width + x stores a 2D grid in a 1D array, one row after another. Part 3 relies on this layout heavily.

Result

It’s only a gradient, but every pixel comes from a ray I built and traced myself. There’s no engine involved at all.

Practice

Sunset: I changed the gradient colors to following:

vec3 horizon(1.0, 0.4, 0.0f);		// orange
vec3 night(0.35, 0.0f, 0.3); // dark blue

Upside down: I replaced height - 1 - y with y

Stretch: I made window 960 × 540.

Sideways sky. I blended on dir.x() instead of dir.y()

A moon : I added following in the sky_color function

	vec3 moonDir = unit_vector(vec3(0.3f, 0.3f, -.3f));
	if (dot(dir, moonDir) > 0.995f)
	{
		return vec3(1.0f, 0.95f, 0.7f);   // pale yellow
	}

Next: Part 2, Hitting a sphere. We’ll place a sphere one unit in front of the camera, solve a quadratic equation to find where each ray hits it, and use the surface normal both for lighting and for carving the jack-o’-lantern’s face.

Credits & Source

1 Comment

Leave a Comment