Terra
Case Study
Overview
A comic-book logistics sim for Brisbane. Draw roads over real city streets and watch self-driving cars teach themselves to drive them, then chart sea lanes and airways and run the whole network from a live dashboard.
Cars learn real routes from seven ray sensors. An offline C++ and PyTorch trainer produces a brain in about 40 seconds that completes all 40 test routes, including 8 it never trained on, and parity tests keep the browser, C# and C++ engines in step.
Where it started
I love Civilization and The Sims: planning a city, laying the roads, and watching everything come to life on top of them.
My dad’s Tesla drives itself with AI, and I wanted to learn the logic behind it. What does the car actually see, and how does it decide when to steer, brake or keep going? Terra puts the two together: a city builder where you build the roads and the cars teach themselves to drive them.
Build the roads
Roads are a graph you draw over real Brisbane streets from OpenStreetMap. A Web Worker turns that graph into rounded road envelopes, lane guides, buildings and trees in about 150 ms for the CBD, and Stop, Give Way, traffic light and crossing markings snap to the left-hand lanes.
What the car sees
Each car casts seven rays and reads how close the nearest kerb or car is along each one, from 0 (nothing in range) to 1 (touching). Those readings, plus its bearing to the route, its speed and its offset from the lane centre, go into a small neural network whose four outputs press the pedals and turn the wheel.
web/src/engine/ai/car.js
update(env) {
if (!this.done) {
this.#move();
this.polygon = this.#createPolygon();
this.damaged = this.#assessDamage(env);
this.age++;
}
if (this.sensor) {
this.sensor.update(this, {
grid: env.grid,
segments: env.segments,
polygons: env.traffic?.map((c) => c.polygon),
});
if (this.useBrain && !this.done) {
const inputs = this.sensor.values().concat(this.extras);
const out = NeuralNetwork.feedForward(inputs, this.brain);
this.controls.forward = out[0] === 1;
this.controls.left = out[1] === 1;
this.controls.right = out[2] === 1;
this.controls.reverse = out[3] === 1;
}
}
}
Learning by survival
There’s no training data. A generation of cars sets off with random brains, and the one that gets furthest along the route without crashing is kept. The next generation is that brain mutated by anything from small tweaks to bold leaps, with some crossover from the runner-up. When a generation stalls on the same corner, the trainer widens the search and mixes in fresh random brains.
web/src/engine/ai/trainer.js
nextBrains() {
const n = this.populationSize;
if (!this.best) return new Array(n).fill(null);
const brains = [NeuralNetwork.clone(this.best)];
// Stuck on the same corner? Widen the search, and add some fresh random brains.
const boost = Math.min(4, 1 + this.stagnant * 0.35);
const fresh = Math.floor(n * (this.stagnant > 3 ? 0.15 : 0.05));
for (let i = 1; i < n; i++) {
if (i >= n - fresh) {
brains.push(null);
continue;
}
const spread = (0.25 + 1.5 * (i / n)) * boost;
let child;
if (this.runnerUp && NeuralNetwork.sameShape(this.best, this.runnerUp) && this.random() < 0.2) {
child = NeuralNetwork.crossover(this.best, this.runnerUp, this.random);
} else {
child = NeuralNetwork.clone(this.best);
}
NeuralNetwork.mutate(child, Math.min(1, this.mutation * spread), this.random);
brains.push(child);
}
return brains;
}
Ships, planes and an ops floor
The same sensors and trainer teach ships to thread the North-West Channel out of Moreton Bay and planes to fly around a drifting cyclone. Every delivery pays coins into the Depot, an idle game that keeps earning while you’re away, and a 3D ops floor and a live dashboard run the whole network.
One simulation, two languages
The logistics sim runs in the browser and on the .NET API. The C# version is a line-for-line port of the JavaScript, with the same random number generator, call order and rounding, and parity tests replay fixtures from the real browser engine to prove both produce the same shipments and KPIs from the same seed.
api/Terra.Api.Tests/ParityTests.cs
[Fact]
public void Simulator_ProducesTheSameShipmentsAsTheBrowser()
{
var sim = Sim();
var l = Fixture["logistics"]!;
Assert.Equal(l["time"]!.GetValue<double>(), sim.Time);
Assert.Equal(l["shipmentCount"]!.GetValue<int>(), sim.Shipments.Count);
var expected = l["firstShipments"]!.AsArray();
for (var i = 0; i < expected.Count; i++)
{
var e = expected[i]!;
var s = sim.Shipments[i];
Assert.Equal(e["id"]!.GetValue<string>(), s.Id);
Assert.Equal(e["status"]!.GetValue<string>(), s.Status);
Close(e["costAud"]!.GetValue<double>(), s.CostAud, $"{s.Id} cost");
Close(e["etaAt"]!.GetValue<double>(), s.EtaAt, $"{s.Id} eta");
}
}
Terra Trainer
In the browser, cars learn on one thread at up to 60 frames a second. Version 1.1 adds Terra Trainer, which moves training off the page. A headless C++ copy of the car sim runs every car on every core, PyTorch trainers search for better brains, and the best one is exported in the exact format the app already imports. The JavaScript engine stays the source of truth; the C++ only exists to train.
That only works if the C++ car really is the browser's car. Parity tests replay fixtures from the browser engine, and sensor readings, decisions and positions agree to within 10⁻¹² over 200 single steps and 12 whole drives, which end on the same frame.
trainer/py/terra_trainer/es.py
for g in range(1, generations + 1):
pop = np.asarray(cma_es.ask())
# every brain drives every route, in parallel C++ threads
res = world.run_episodes(pop, tasks=batch, threads=threads)
fit = res["score"].mean(1)
cma_es.tell(list(pop), list(-fit))
centre = np.asarray(cma_es.mean)
# Elitism for export: score the new centre and this generation's champion on every route.
champion = pop[int(np.argmax(fit))]
ev, tr, ho = evaluate(np.stack([centre, champion]))
k = int(np.argmax(tr))
if tr[k] > best["train"]:
best.update(train=float(tr[k]), holdout=float(ho[k]), params=(centre, champion)[k].copy(), generation=g)
What the comparison showed
I compared four training methods, three runs each, on 32 routes across Brisbane, the Gold Coast, Sydney and Melbourne, holding 8 routes back to test whether a brain can drive roads it has never seen. CMA-ES finished nearly every route on every run, in a median of 5.8 seconds. The brain that ships with Terra was trained from scratch in about 40 seconds and completes all 40 routes, including the 8 held back.
The honest finding is that the browser's own genetic algorithm is a strong baseline: it needed fewer generations than CMA-ES. The speed-up comes from running cars in parallel in C++ (6.1 million car-steps a second on 8 threads, against about 350,000 in Node), not from a cleverer optimiser. Logging 1.2 million crashes by road segment showed where cars fail: 69% mid-route, bunched on a handful of tricky corners.