Journal
Voxels11 min read

A Bridge Over a Pond, and Other Hard Problems

I built a courtyard with a bridge over the pond to see whether the engine held up, and lost a lion along the way.

By James

A stone arch bridge with a balustrade standing in the voxel flower meadow, built by the engine's architecture kit.

A couple of entries ago I said the hard part of a voxel engine isn't how it looks but how much stuff it has to hold: millions of tiny voxels, all of them editable, all of them needing to reach the screen in a sixtieth of a second.

So the next thing I did was add a lot more of it - textured stone, reflections, imported models. Then I built a courtyard with a bridge over the pond to see whether any of it held up. Along the way: fire bowls that looked like fluorescent tubes, and a lion that turned into a paving slab.

Building with real materials

Until now, building materials were plain colours. The first big addition was a palette of textured ones: brick, stone blocks, cobblestone, marble and planks. Each starts life as a public-domain photo texture, gets baked down to one colour per voxel, and is laid out by world position rather than per block. So two cubes of brick placed side by side join into one continuous wall, with no seam where they meet, and carving into a wall shows the pattern carrying on inside.

Some took a few goes. My first cobblestone came out looking like pale paving slabs with patchy joints. A different texture fixed it.

A brick block and a plank wall standing in the meadow, with a doorway carved through the plank wall showing the meadow behind it.
Brick and planks placed in the meadow, with a doorway carved through the plank wall.

The view from eighty metres

Past fifty metres the world is drawn at coarser resolution. That's standard practice and it saves a lot of memory. The catch is that your edits have to show up correctly in the coarse version too, and mine didn't.

Carve a doorway through a wall and, from far enough away, it had a closed skin across it. Place a block and carve it away again, and a ghost of it stayed standing in the distance. Paint a block and it kept an unpainted edge. Set a floor flush into the grass and it vanished once you walked off. Each of these had its own little fix, and each fix caused a new small problem somewhere else. I took that as a sign the approach was wrong, and replaced it. Now the distance shows what you built.

The same view after the fix: the doorway is open, the carved-away block is gone and the floors show.
A zoomed view from about 90 metres of blocks built in the meadow: the doorway reads closed, a carved-away block still stands and the floors are missing.
BeforeAfter
The same builds seen from about 90 metres away, zoomed in. Before: a closed doorway, a block that shouldn't be there and no floors. After: what was actually built.

This work also turned up a performance mystery. For a while, edits made inside a tree's crown would sometimes take nearly six milliseconds instead of about two. Crowns are dense, so the obvious suspect was the crown. I measured the work itself: identical every time. The same edit took two milliseconds on the CPU in isolation and sometimes six in the running engine. The culprit was outside the engine - other load on the machine was stretching whole frames now and then, crown or no crown.

So the tree was innocent. These days I time the work itself as well as the frame.

Warmer light

Next came a pass on the look. The sun is now drawn at four times its real size, two degrees across. That's not physically right, but it makes shadows soften the further they fall from whatever casts them, the way they do in paintings and, less dramatically, in real life. Bright things now glow slightly into their surroundings, the white balance is warmer, and the haze is a quarter as thick as it was, so the far treeline keeps its colour.

Things that shine

Then reflections. There's now a whole page of shiny materials: polished marble, polished planks, gold, copper, iron, polished stone and a mirror, all using a standard physically based model.

Two numbers do most of the work. The first is how much light a material reflects when you look straight at it. Water reflects about 2%, which is why a pond looks like a window from above. Gold reflects about 100% of red, 77% of green and 34% of blue, which is why it looks gold; the engine's metals use measured values like these rather than my opinion of what gold looks like. As the viewing angle flattens, every material heads towards a mirror, which is why the far side of the pond reflects the trees. The second number is roughness, which decides whether a reflection is a sharp image or a soft sheen.

One thing surprised me. Polished marble in full sun barely looks polished at all. That turns out to be physics, not a bug: whatever the floor reflects is lit by the same sun, and the floor's own brightness drowns it out. Put the floor in shade and the gloss appears.

The same floor in polished marble, reflecting the sunlit surroundings.
A matte marble floor in shade in front of a brick wall.
MattePolished
The same floor in the shade of a wall, matte and polished.
A row of cubes in the meadow beside the pond: a mirror, gold, copper and iron, each reflecting the flowers and sky in its own colour.
A mirror, gold, copper and iron in the meadow, each reflecting the same flowers in its own colour.

The pond got the same treatment. It now mirrors the sun as a proper bright disc, and its reflection holds still while you move, where it used to smear the trees into a green streak. The testing entry has the before and after.

It also came in at roughly double its frame-time allowance. I wrote that down and kept going.

Stone, colour and a very full meadow

The meadow got a colour pass. Each broadleaf tree now picks its own autumn colour, from lime to crimson, and the flowers come in five colours spread evenly, instead of the pastel carpet from before.

Red, orange, yellow and green voxel tree crowns above a dense meadow of red, violet, blue and orange flowers.
Autumn crowns over the flower meadow.

Then stone. When the textured materials first arrived, their mortar joints were faked at draw time, one voxel deep. Now the joints are carved into the voxels themselves, up to three deep. There are new stones too: rough fieldstone, small blocks and white blocks. Fieldstone has proud stones with deep, dark gaps between them, and the white blocks step down twice to each joint. The white blocks came out sandstone-coloured the first time and needed another go. Because the joints are real, everything else just works with them: shadows fall into them, light bounces around inside them, and a block placed into a joint sits flush with the face. It also turned out cheaper to draw than the fake version.

The first version kept punching straight through thin walls, leaving them full of tiny windows. There's now a guard against that, and a set of deliberately nasty test walls to make sure it stays fixed.

The same fieldstone wall with joints up to three voxels deep, the stones standing proud with dark gaps between them.
A fieldstone wall with joints one voxel deep, the stones reading mostly as a flat pattern.
One voxel deepCarved joints
The same fieldstone wall with shallow joints and with carved ones.

Nearly halving the frame

By this point light, materials and reflections had eaten a lot of frame time. The centre view of my test world cost nearly 18 milliseconds a frame against a target of 16.6, a steady 60 frames a second, and several views were well over. The worst, looking at the sun in the pond, took nearly 34.

So I stopped adding things and measured instead. I built tools that break a frame down stage by stage and draw a heat map of where the time goes.

A false-colour heat map of the glade view, the meadow and trees in cool blue and green and the pond in hot yellow and orange.
Where the frame spent its time at the start of the performance work. Cool is cheap, hot is expensive, and the pond is the hot spot.

Two changes did most of the work. The ray tracing hardware was being handed boxes much larger than the voxels inside them, so rays kept stopping to check empty space. Tightening those boxes paid off on every view. And the light bouncing around underneath the pond's surface was being fully path traced, at great expense, for a result you can barely see through the water. That's now estimated instead of traced. I checked the estimate against the traced version, and the pond floor's brightness agrees to within a tenth of a percent.

From paired runs of the before and after builds:

ViewBeforeAfter
Centre of the glade17.8 ms9.8 ms
Forest edge19.6 ms12.1 ms
Walking at golden hour20.3 ms12.0 ms
Looking at the sun in the pond34.0 ms12.4 ms
Dusk with a lamp32.7 ms12.7 ms
Through a glass wall25.9 ms16.4 ms

Every standard view is now under budget. The glass wall has the least headroom, about a quarter of a millisecond. The second light bounce is still switched off, because turning it on pushes five views back over.

Real models as voxels

Up to now everything in the world was generated or built by hand. Now ordinary 3D models can come in too. The importer takes a textured model and bakes it into coloured 5 cm voxels. The models keep their colours, the metal ones shine like metal, and anything meant to glow does glow and lights what's around it. Once placed, a prop is just more voxels: you can turn it, carve it, paint it and undo it like any other edit. It shows up at a distance too, which the first version didn't manage - imported props simply vanished beyond fifty metres.

The first set is nine free models: a painted bench, two lanterns, a street lamp, a stone fire pit, a statue, a marble bust, a brass urn and a ceramic pot.

A voxelised stone statue standing on the bank of the pond, its shape and weathered colouring kept at 5 cm.
An imported statue on the bank of the pond, at 5 cm.

There was also a tenth model, a lion's head. At 5 cm it came out as a lumpy grey tile with no discernible lion in it. It was retired with honours.

Turning a model into voxels has two halves: finding its surface, and deciding what's inside. The surface is the easy half. For the inside, a classic trick is an exterior flood fill: mark every voxel the surface passes through, pour "outside" in from a corner of the bounding box, and whatever the flood never reaches must be inside.

// Solid voxelisation by exterior flood fill.
// 1. Mark every voxel the model's surface passes through.
foreach (var tri in mesh.Triangles)
    foreach (var v in VoxelsTouchedBy(tri))
        grid[v] = Cell.Surface;

// 2. Flood "outside" in from a corner of the box, which is padded so it starts empty.
var queue = new Queue<Int3>();
queue.Enqueue(Int3.Zero);
grid[Int3.Zero] = Cell.Outside;
while (queue.Count > 0)
{
    var c = queue.Dequeue();
    foreach (var n in Neighbours6(c))
        if (InBounds(n) && grid[n] == Cell.Empty)
        {
            grid[n] = Cell.Outside;
            queue.Enqueue(n);
        }
}

// 3. Whatever the flood never reached is inside the model: fill it.
foreach (var c in grid.Cells)
    if (grid[c] == Cell.Empty) grid[c] = Cell.Solid;

It has one weakness, and real models find it immediately. If the surface has a gap anywhere, the flood pours through it and fills the inside with "outside", so the model comes out hollow. Many 3D scans are open at the bottom, where the model stood on the ground. The fix for those was to treat the ground under a model as a lid before flooding, which made the statue and the street lamp solid. A few models, like the lanterns, have gaps in other places too, so carve into one and you find a hollow shell. For models that are properly closed, the importer uses a different inside test, based on the winding number, which doesn't care about gaps in the first place.

Every prop in a scene also shares a single palette of at most 112 colours, because every voxel is a single byte indexing one material table, and the terrain and the building materials need their share of it too. Picking those colours is a clustering problem, and I use the standard tool for it, k-means, with one change: distances are measured in Oklab, a colour space designed so that equal distances look like equal differences to the eye. In plain RGB, "nearest" can pick a colour that's numerically close but visibly wrong. Across all nine props the average error comes out at about one just-noticeable difference or less - roughly the smallest difference the eye can pick out side by side.

A voxelised ring-shaped stone fire pit set into the flower meadow.
The imported stone fire pit, set into the meadow.

Building the Court

All of this needed a proper test, so I built something. First an architecture kit: walls with arched openings, columns, balustrades, stairs, an arched bridge, terraces, a portico and fire bowls, each generated from a few parameters. The bridge alone is about half a million voxels.

Then I used the kit and the props to build a small showcase on the glade: a paved courtyard with a cobbled path down the middle, a fieldstone gate wall with a round arch, an arcade and a marble colonnade, a bridge over the pond leading to a temple terrace with a portico, and eight fire bowls, statues, benches, lanterns and street lamps to dress it. I call it the Court.

The arched bridge crossing the pond, seen from the meadow, with the arcade to the left and a street lamp at the far end.
The bridge over the pond, with the arcade beyond it.
A marble colonnade beside the courtyard paving, with a fire bowl on a pedestal, street lamps and the arcade in the distance.
Along the colonnade, with a fire bowl on its pedestal and the arcade beyond.
A fieldstone wall seen square-on, with a round arch dressed in white stone framing a view of the meadow and autumn trees.
The fieldstone gate. Without the white stone dressing around the arch, it looked more like a ruin than a gate.
The temple on its terrace, a white stone building with a columned portico and a brick roof, with a fire bowl in the foreground.
The temple front on its terrace.
The white stone arcade seen from the flower meadow outside the courtyard, with a bench and lanterns visible through the arches.
The arcade from outside the courtyard.

The Court turned out cheap. It adds more than five million voxels of architecture and props, and roughly 10 MB of GPU memory. Several views are actually cheaper than the same view of the plain meadow, because paving is far simpler to draw than a field of grass and flowers. Looking down the courtyard costs about 7.4 milliseconds, against 8.7 for the meadow it replaced.

Looking down the paved courtyard along a cobbled path toward the bridge, with the colonnade on the left and the arcade on the right.
Down the middle of the courtyard toward the bridge.

At dusk the fire bowls carry the scene's warm light. In the first build their flames came out as tall, overexposed white shapes, and each bowl counted as dozens of separate lights, which got expensive fast. The flames are now smaller, orange, and about half as many lights. The street lamps came out a clinical white too, and now glow a warm yellow.

The same fire bowl with a smaller orange flame.
A fire bowl at dusk with a large cream-white flame.
Too whiteOrange
The same fire bowl at dusk with a brighter flame and with the one I kept. The brighter flame came out whiter rather than warmer.
The courtyard at dusk, looking toward the stairs up to the bridge, with orange fire bowls on either side and warm street lamps against an orange sky.
Dusk in the courtyard, with the fire bowls and street lamps lit.
The arcade at dusk, the sunset glowing through its arches, with a lantern beside a bench and a street lamp.
The arcade at dusk.

I also rebuilt the whole Court at 4 cm voxels instead of 5, to see whether it was worth it. The balusters and the busts do look crisper. It also costs about 60% more GPU memory, takes about three quarters longer to generate, and blows through the renderer's limit on separate pieces. I'm staying at 5 cm.

Every view of the Court is under budget. Next is motion: water, weather, fire and animals.