Open full screen ↗
#include "rt.h"
#include <cmath>
#include <memory>
#include <vector>
namespace {
constexpr double pi = 3.14159265358979323846;
constexpr double infinity = 1e30;
constexpr int max_depth = 12;
struct vec3 {
double x = 0, y = 0, z = 0;
vec3 operator-() const { return {-x, -y, -z}; }
vec3 &operator+=(const vec3 &v) {
x += v.x;
y += v.y;
z += v.z;
return *this;
}
double length_squared() const { return x * x + y * y + z * z; }
double length() const { return std::sqrt(length_squared()); }
bool near_zero() const {
constexpr double s = 1e-8;
return std::fabs(x) < s && std::fabs(y) < s && std::fabs(z) < s;
}
};
using point3 = vec3;
using colour = vec3;
vec3 operator+(const vec3 &a, const vec3 &b) {
return {a.x + b.x, a.y + b.y, a.z + b.z};
}
vec3 operator-(const vec3 &a, const vec3 &b) {
return {a.x - b.x, a.y - b.y, a.z - b.z};
}
vec3 operator*(const vec3 &a, const vec3 &b) {
return {a.x * b.x, a.y * b.y, a.z * b.z};
}
vec3 operator*(double t, const vec3 &v) { return {t * v.x, t * v.y, t * v.z}; }
vec3 operator/(const vec3 &v, double t) { return (1 / t) * v; }
double dot(const vec3 &a, const vec3 &b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
vec3 cross(const vec3 &a, const vec3 &b) {
return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x};
}
vec3 unit(const vec3 &v) { return v / v.length(); }
vec3 reflect(const vec3 &v, const vec3 &n) { return v - 2 * dot(v, n) * n; }
vec3 refract(const vec3 &uv, const vec3 &n, double eta_ratio) {
double cos_theta = std::fmin(dot(-uv, n), 1.0);
vec3 perp = eta_ratio * (uv + cos_theta * n);
vec3 parallel = -std::sqrt(std::fabs(1.0 - perp.length_squared())) * n;
return perp + parallel;
}
// xorshift64*: deterministic for a given seed, so a scene is reproducible.
uint64_t rng_state = 1;
double random_double() {
rng_state ^= rng_state >> 12;
rng_state ^= rng_state << 25;
rng_state ^= rng_state >> 27;
return double((rng_state * 0x2545F4914F6CDD1DULL) >> 11) * 0x1.0p-53;
}
double random_double(double lo, double hi) {
return lo + (hi - lo) * random_double();
}
vec3 random_vec(double lo, double hi) {
return {random_double(lo, hi), random_double(lo, hi),
random_double(lo, hi)};
}
vec3 random_unit_vector() {
while (true) {
vec3 p = random_vec(-1, 1);
double l2 = p.length_squared();
if (1e-160 < l2 && l2 <= 1)
return p / std::sqrt(l2);
}
}
vec3 random_in_unit_disk() {
while (true) {
vec3 p{random_double(-1, 1), random_double(-1, 1), 0};
if (p.length_squared() < 1)
return p;
}
}
struct ray {
point3 origin;
vec3 dir;
point3 at(double t) const { return origin + t * dir; }
};
struct material;
struct hit_record {
point3 p;
vec3 normal;
const material *mat = nullptr;
double t = 0;
bool front_face = false;
};
struct material {
enum kind { lambertian, metal, dielectric } type;
colour albedo;
double fuzz = 0;
double ior = 1;
bool scatter(const ray &in, const hit_record &rec, colour &attenuation,
ray &out) const {
switch (type) {
case lambertian: {
vec3 dir = rec.normal + random_unit_vector();
if (dir.near_zero())
dir = rec.normal;
out = {rec.p, dir};
attenuation = albedo;
return true;
}
case metal: {
vec3 reflected =
unit(reflect(in.dir, rec.normal)) + fuzz * random_unit_vector();
out = {rec.p, reflected};
attenuation = albedo;
return dot(reflected, rec.normal) > 0;
}
case dielectric: {
attenuation = {1, 1, 1};
double ri = rec.front_face ? 1.0 / ior : ior;
vec3 u = unit(in.dir);
double cos_theta = std::fmin(dot(-u, rec.normal), 1.0);
double sin_theta = std::sqrt(1.0 - cos_theta * cos_theta);
double r0 = (1 - ri) / (1 + ri);
r0 *= r0;
double schlick = r0 + (1 - r0) * std::pow(1 - cos_theta, 5);
bool reflect_only =
ri * sin_theta > 1.0 || schlick > random_double();
out = {rec.p, reflect_only ? reflect(u, rec.normal)
: refract(u, rec.normal, ri)};
return true;
}
}
return false;
}
};
struct sphere {
point3 centre;
double radius;
int mat;
};
struct scene {
std::vector<sphere> spheres;
std::vector<material> materials;
int add_material(material m) {
materials.push_back(m);
return int(materials.size()) - 1;
}
bool hit(const ray &r, double t_min, double t_max, hit_record &rec) const {
bool hit_any = false;
double a = r.dir.length_squared();
for (const sphere &s : spheres) {
vec3 oc = s.centre - r.origin;
double h = dot(r.dir, oc);
double c = oc.length_squared() - s.radius * s.radius;
double disc = h * h - a * c;
if (disc < 0)
continue;
double sq = std::sqrt(disc);
double t = (h - sq) / a;
if (t <= t_min || t >= t_max) {
t = (h + sq) / a;
if (t <= t_min || t >= t_max)
continue;
}
t_max = t;
hit_any = true;
rec.t = t;
rec.p = r.at(t);
vec3 outward = (rec.p - s.centre) / s.radius;
rec.front_face = dot(r.dir, outward) < 0;
rec.normal = rec.front_face ? outward : -outward;
rec.mat = &materials[s.mat];
}
return hit_any;
}
};
struct camera {
point3 origin, pixel00;
vec3 du, dv, defocus_u, defocus_v;
camera(int w, int h, point3 from, point3 at, double vfov,
double aperture_deg, double focus_dist) {
vec3 up{0, 1, 0};
double half_h = std::tan(vfov * pi / 360) * focus_dist;
double view_h = 2 * half_h;
double view_w = view_h * double(w) / h;
vec3 back = unit(from - at);
vec3 right = unit(cross(up, back));
vec3 cam_up = cross(back, right);
origin = from;
du = (view_w / w) * right;
dv = (view_h / h) * -cam_up;
point3 upper_left =
from - focus_dist * back - (view_w / 2) * right + half_h * cam_up;
pixel00 = upper_left + 0.5 * (du + dv);
double defocus_r = focus_dist * std::tan(aperture_deg * pi / 360);
defocus_u = defocus_r * right;
defocus_v = defocus_r * cam_up;
}
ray get_ray(int i, int j) const {
point3 sample = pixel00 + (i + random_double() - 0.5) * du +
(j + random_double() - 0.5) * dv;
vec3 d = random_in_unit_disk();
point3 from = origin + d.x * defocus_u + d.y * defocus_v;
return {from, sample - from};
}
};
colour sky(const ray &r) {
double a = 0.5 * (unit(r.dir).y + 1.0);
return (1.0 - a) * colour{1.0, 1.0, 1.0} + a * colour{0.5, 0.7, 1.0};
}
// Iterative so deep glass bounces don't grow the (small) wasm stack.
colour trace(ray r, const scene &world) {
colour throughput{1, 1, 1};
for (int depth = 0; depth < max_depth; depth++) {
hit_record rec;
if (!world.hit(r, 0.001, infinity, rec))
return throughput * sky(r);
colour attenuation;
ray scattered;
if (!rec.mat->scatter(r, rec, attenuation, scattered))
return {0, 0, 0};
throughput = throughput * attenuation;
r = scattered;
}
return {0, 0, 0};
}
scene make_scene() {
scene world;
int ground = world.add_material({material::lambertian, {0.5, 0.5, 0.5}});
world.spheres.push_back({{0, -1000, 0}, 1000, ground});
for (int a = -5; a < 5; a++) {
for (int b = -5; b < 5; b++) {
point3 centre{a + 0.9 * random_double(), 0.2,
b + 0.9 * random_double()};
if ((centre - point3{4, 0.2, 0}).length() <= 0.9)
continue;
double choose = random_double();
material m;
if (choose < 0.7)
m = {material::lambertian, random_vec(0, 1) * random_vec(0, 1)};
else if (choose < 0.9)
m = {material::metal, random_vec(0.5, 1),
random_double(0, 0.4)};
else
m = {material::dielectric, {1, 1, 1}, 0, 1.5};
world.spheres.push_back({centre, 0.2, world.add_material(m)});
}
}
world.spheres.push_back(
{{0, 1, 0},
1.0,
world.add_material({material::dielectric, {1, 1, 1}, 0, 1.5})});
world.spheres.push_back(
{{-4, 1, 0},
1.0,
world.add_material({material::lambertian, {0.4, 0.2, 0.1}})});
world.spheres.push_back(
{{4, 1, 0},
1.0,
world.add_material({material::metal, {0.7, 0.6, 0.5}, 0.0})});
return world;
}
double linear_to_gamma(double c) { return c > 0 ? std::sqrt(c) : 0; }
uint8_t to_byte(double c) {
c = linear_to_gamma(c);
return uint8_t(256 * (c < 0 ? 0 : c > 0.999 ? 0.999 : c));
}
struct renderer {
int width, height;
scene world;
camera cam;
std::vector<colour> accum;
std::vector<uint8_t> rgba;
int row = 0;
int samples = 0;
renderer(int w, int h)
: width(w), height(h), world(make_scene()),
cam(w, h, {13, 2, 3}, {0, 0, 0}, 20, 0.6, 10.0), accum(size_t(w) * h),
rgba(size_t(w) * h * 4, 255) {}
void trace_row(int j) {
double inv = 1.0 / (samples + 1);
for (int i = 0; i < width; i++) {
size_t k = size_t(j) * width + i;
accum[k] += trace(cam.get_ray(i, j), world);
colour c = inv * accum[k];
rgba[4 * k + 0] = to_byte(c.x);
rgba[4 * k + 1] = to_byte(c.y);
rgba[4 * k + 2] = to_byte(c.z);
}
}
};
std::unique_ptr<renderer> current;
} // namespace
extern "C" {
void rt_init(int width, int height, unsigned seed) {
rng_state =
0x9E3779B97F4A7C15ULL ^ (uint64_t(seed) * 0xBF58476D1CE4E5B9ULL);
if (rng_state == 0)
rng_state = 1;
current = std::make_unique<renderer>(width, height);
}
int rt_step(int rows) {
renderer &r = *current;
for (int n = 0; n < rows; n++) {
r.trace_row(r.row);
if (++r.row == r.height) {
r.row = 0;
r.samples++;
}
}
return r.samples;
}
uint8_t *rt_pixels() { return current->rgba.data(); }
int rt_samples() { return current->samples; }
}
#pragma once
#include <cstdint>
// Progressive renderer: every pass adds one sample to every pixel, so the
// image sharpens over time. rt_step traces a few rows at a time, so the
// browser can paint between calls without freezing.
extern "C" {
void rt_init(int width, int height, unsigned seed);
int rt_step(int rows);
uint8_t *rt_pixels();
int rt_samples();
}
#include "rt.h"
#include <cstdlib>
#include <iostream>
int main(int argc, char **argv) {
int width = 640;
int height = 360;
int samples = argc > 1 ? std::atoi(argv[1]) : 32;
unsigned seed = argc > 2 ? unsigned(std::atoi(argv[2])) : 1;
rt_init(width, height, seed);
while (rt_step(height) < samples)
std::clog << "\rsamples " << rt_samples() << '/' << samples
<< std::flush;
std::clog << "\rdone" << std::string(20, ' ') << '\n';
const uint8_t *px = rt_pixels();
std::cout << "P3\n" << width << ' ' << height << "\n255\n";
for (int k = 0; k < width * height; k++)
std::cout << int(px[4 * k]) << ' ' << int(px[4 * k + 1]) << ' '
<< int(px[4 * k + 2]) << '\n';
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ray tracer (C++ → WebAssembly)</title>
<style>
html, body { margin: 0; height: 100%; background: #07090f; color: #c9d2e3; font: 14px/1.4 system-ui, sans-serif; }
body { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; padding: 10px; box-sizing: border-box; }
canvas { max-width: 100%; max-height: calc(100% - 48px); aspect-ratio: 16 / 9; background: #000; border-radius: 4px; }
.bar { display: flex; gap: 14px; align-items: center; font-variant-numeric: tabular-nums; }
button { font: inherit; color: inherit; background: #1a2238; border: 1px solid #34406a; border-radius: 4px; padding: 4px 12px; cursor: pointer; }
button:hover { background: #24305a; }
</style>
</head>
<body>
<canvas id="c" width="640" height="360"></canvas>
<div class="bar">
<span id="status">loading…</span>
<button id="pause">Pause</button>
<button id="reseed">New scene</button>
</div>
<script type="module">
import createModule from './rt.js';
const W = 640, H = 360, TARGET = 256, BUDGET_MS = 14;
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
const image = ctx.createImageData(W, H);
const status = document.getElementById('status');
const pauseBtn = document.getElementById('pause');
const rt = await createModule();
let seed = 1, paused = false, started = 0;
function reset() {
rt._rt_init(W, H, seed);
started = performance.now();
}
function frame() {
const samples = rt._rt_samples();
if (!paused && samples < TARGET) {
const end = performance.now() + BUDGET_MS;
while (performance.now() < end) rt._rt_step(4);
image.data.set(rt.HEAPU8.subarray(rt._rt_pixels(), rt._rt_pixels() + W * H * 4));
ctx.putImageData(image, 0, 0);
}
const secs = ((performance.now() - started) / 1000).toFixed(1);
status.textContent = samples >= TARGET
? `done: ${TARGET} samples/pixel in ${secs}s`
: `${paused ? 'paused' : 'rendering'}: ${samples}/${TARGET} samples/pixel`;
requestAnimationFrame(frame);
}
pauseBtn.onclick = () => { paused = !paused; pauseBtn.textContent = paused ? 'Resume' : 'Pause'; };
document.getElementById('reseed').onclick = () => { seed++; reset(); };
reset();
requestAnimationFrame(frame);
</script>
</body>
</html>
.PHONY: dev web
SRC = main.cpp rt.cpp
OUT ?= build
dev:
clang-format -i --style='{BasedOnStyle: LLVM, UseTab: Always, IndentWidth: 4, TabWidth: 4, AlignEscapedNewlines: DontAlign}' $(SRC) rt.h && g++ -std=c++20 -O0 -g -fsanitize=address,undefined -fno-omit-frame-pointer $(SRC) -o main && ./main 8 > image.ppm && open image.ppm
# Used by the site's build.py: emits rt.js + rt.wasm + index.html into $(OUT).
web:
mkdir -p $(OUT)
em++ -std=c++20 -O3 rt.cpp -o $(OUT)/rt.js \
-sMODULARIZE -sEXPORT_ES6 -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH \
-sEXPORTED_FUNCTIONS=_rt_init,_rt_step,_rt_pixels,_rt_samples \
-sEXPORTED_RUNTIME_METHODS=HEAPU8
cp index.html $(OUT)/
The image refines in the browser. Each pass adds one sample to every pixel.
- Wrote a path tracer in C++ with no dependencies: Lambertian, metal (with fuzz) and glass (Schlick reflectance) materials, a thin-lens camera with depth of field, and gamma correction.
- Compiled the same code to WebAssembly with Emscripten. The renderer traces a few rows per call, so the page paints progress at a steady frame rate instead of freezing.
- Kept a native build (
make dev) that writes a PPM image, with AddressSanitizer and UBSan on.