Ray Tracer: C++ to WebAssembly

October 5, 2026 · C++, WebAssembly

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; }
}

The image refines in the browser. Each pass adds one sample to every pixel.

← NEAT Twin-Stick Shooter Agent
→ Real Time Chatroom