Architecture snapshot: December 2026. This article documents Play2Train's volumetric terrain generation, erosion, hydrology, meshing, and persistence stack (src/engine/runtime/terrain/TerrainVolumeData.h/.cpp, TerrainMaterialWeights.h, TerrainNoise.h, TerrainGenerator.h/.cpp, TerrainErosion.h/.cpp, TerrainHydrology.h/.cpp, TerrainSurfaceData.h, TerrainNormals.h, TerrainAO.h, TerrainLayers.h/.cpp, and TerrainFormat.md — 2,369 lines of C++23 and specification inside the reusable Play2Train SDK, paired with the 249-line game-side P2TTRN v4 serializer in src/game/systems/TerrainPersistence.h/.cpp and the native regression suites in unit-tests/Engine/Terrain/) inside Gattic's closed-source Play2Train SDK. Both Robot Universe and PloppyPals build on Play2Train.
Most 3D games cheat when they build hills and valleys. Under the hood, their ground is not a solid earth you can carve into — it is a flat rubber sheet stretched up and down over a grid of invisible pins. Each spot on the map gets one height number, and that is all the engine knows. The moment a player tries to dig a tunnel into a cliffside, sculpt a natural stone arch, or carve an overhanging cave, the rubber sheet runs out of tricks: a single sheet can only sit at one altitude at any (x, z) coordinate.
A second problem shows up even before anyone picks up a shovel. Procedural terrain generators usually stack bumpy fractal noise and drop thousands of simulated raindrops across the hills. Those raindrops carve convincing little gullies on steep slopes, then get trapped in random puddles a few meters later. Zoom out over the landscape and instead of streams flowing down valleys to the sea, you see disconnected pits and isolated scars that never join into real watersheds.
Play2Train solves both problems together with a terrain architecture built on three interlocking layers:
- An editable 3D scalar density field with independent material blends. Rather than a flat elevation sheet, terrain is stored as a 3D grid of
UNORM8density values (kIsoDensity = 128) paired with independent 3-byte normalized material weights (grass,sand,rock, and implicitsnow). Meshing happens on demand in64 × 64 × 64chunks via Surface Nets, turning the density field into smooth, manifold-friendly triangles that support true caves, arches, and live brush editing. - Layered procedural generation capped by a deterministic hydrology pass. Initial worlds are synthesized by stacking domain-warped ridged peaks, hydraulic droplet erosion, and thermal talus slumping — followed by a zero-RNG, order-stable hydrology pass (
TerrainHydrology.cpp): Barnes priority-flood depression filling, D8 steepest-descent flow accumulation, logarithmic stream carving, alluvial valley sedimentation, and localized bank relaxation so disconnected erosion scars become continuous drainage networks. - Run-length encoded
P2TTRN v4persistence without vertex dumps. Worlds never save baked triangle meshes or derived scattering maps to disk. Instead,TerrainPersistencewrites a 76-byte binary header plus 8-byte run-length encoded(count, density, grass, sand, rock)runs over Y-fast columns — compressing a 129.5 MiB production volume down to roughly 6–8 MiB while rebuilding meshes, collision geometry, horizon ambient occlusion, and scatter deterministically on load.
Why a 3D density field beats a flat heightmap
For non-technical readers, compare a pin-art toy with a block of sculptor's clay. A traditional 2D heightfield works like a pin-art frame: you can push pins higher to make mountains or lower to make valleys, and you can drape a painted cloth over the tips, but you can never hollow out a cavern underneath a hill because every pin is solid all the way down. A volumetric density field is the block of clay. Every point in 3D space — below ground, at the surface, and up in the sky — holds a single "fullness" number from 0 (completely empty air) to 255 (solid rock). Wherever fullness crosses the halfway mark of 128, the engine wraps the visible surface of the world.
In Play2Train, that block of clay lives in Engine::TerrainVolumeData (src/engine/runtime/terrain/TerrainVolumeData.h/.cpp), exposed to the scene ECS via the thin TerrainVolume component (src/engine/components/TerrainVolume.h). Every 3D sample stores 4 bytes total:
- 1 byte of scalar density (
std::uint8_t,UNORM8): values< 128are empty air; values>= 128(kIsoDensity = 128) are solid terrain. - 3 bytes of independent material blends (
Engine::TerrainMaterialWeights):grass,sand, androck, each in[0, 255], constrained by the invariantgrass + sand + rock <= 255. The fourth layer — snow — is never stored explicitly; it is the exact remainder255 - grass - sand - rock(static_assert(sizeof(TerrainMaterialWeights) == 3)).
Separating material weights from density means material is not a function of altitude. You can dig into a grassy hillside and expose rock, paint a sandy path across a mountain ridge, or carve a tunnel through snow-capped stone without the engine suddenly re-coloring your edits back into default elevation stripes.
Three subtle storage choices in TerrainVolumeData.cpp and TerrainMaterialWeights.h carry outsized engineering weight:
- Y-fast column memory order. Most 3D voxel engines lay out arrays with X or Z fastest. Play2Train puts Y fastest:
Index(x, y, z) = (z * nx + x) * ny + y. As the comment inTerrainVolumeData.cppnotes, contiguous vertical columns make top-surface scans cache-local and turn every vertical column into two long constant runs (deep solid255below, open air0above) forP2TTRN v4run-length encoding. - Two-cell unsaturated quantization (
127 / dy, never255 / dy). When seeding a 3D volume from a floating-point heightfield (WriteHeightColumn), an intuitive formula might scale density by255 / dyaround the surface. Play2Train discovered that255 / dysaturates one of the two bracketing grid samples to0or255whenever a height does not land cleanly on a half-voxel: for a true height of0.25(withy0 = 0,dy = 1),255 / dyclamps the upper sample to0while setting the lower sample to192, so linear interpolation reconstructs(128 - 192) / (0 - 192) = 0.3333— introducing systematic stair-step terracing! Using128.0f + (height - sampleY) * (127.0f / dy)keeps both bracketing samples unsaturated (160and33), reconstructing32 / 127 = 0.2520and capping vertical quantization error tody / (2 × 127) = dy / 254(under 4 millimeters on a 1-meter vertical step). - Strict height-seeding bounds and largest-remainder material quantization.
InitializeFromHeightsandSetHeightSubRegionvalidate every height before mutating a single sample, accepting only finite heights in[y0, y0 + (ny - 2) * dy](defaulty0 = -64.0f,dy = 1.0f,ny = 129, giving[-64, +63]) so there is always a solid floor sample and at least one air sample above the highest peak — never silently clipping a mountain flat against the volume ceiling. Meanwhile,TerrainMaterialWeights::FromFloatsconverts four floating-point material fractions (grass,sand,rock, implicitsnow) to fouruint8counts summing to255using largest-remainder (Hamilton) apportionment, guaranteeing at most1/255quantization error per layer across all four channels.
// src/engine/runtime/terrain/TerrainVolumeData.cpp
void TerrainVolumeData::WriteHeightColumn(int x, int z, float height)
{
for (int y = 0; y < m_ny; ++y) {
const float sampleY = m_y0 + static_cast<float>(y) * m_dy;
// Keep BOTH samples bracketing the height unsaturated. A 255/dy
// gradient clipped one endpoint and moved a height of .25 to .333.
// The two-cell band limits vertical error to dy/(2*127), rather than
// introducing systematic terracing before meshing and placement.
const float value = 128.0f + (height - sampleY) * (127.0f / m_dy);
m_density[Index(x, y, z)] = static_cast<std::uint8_t>(
std::lround(std::max(0.0f, std::min(255.0f, value))));
}
}From sculpted noise to eroded hills: ridges, droplets, and talus
Before the 3D density volume is even populated, Play2Train synthesizes the initial natural landscape on a deterministic 2D grid (TerrainGenerator::GenerateHeights). Think of the process like a physical terrain workshop with four sequential stations:
- Rough-carving the mountain ranges out of foam with warped ridges, broad rolling lowlands, and sunken basins (
TerrainNoise.h,TerrainGenerator.cpp). - Pouring 60,000 virtual raindrops over the foam to cut gullies and wash sediment downhill, followed by shaking the table so overly steep gravel piles slump to a natural angle of repose (
TerrainErosion.cpp). - Running a global watershed and river pass that connects every trapped puddle into continuous streams, flattens silty valley floors, and softens stream banks (
TerrainHydrology.cpp). - Painting geomorphology-aware biomes (grass, sand, rock, snow) onto the terrain and baking both heights and weights into the 3D volume (
TerrainGenerator::GenerateWeights→TerrainVolumeData).
Stage 1: Analytic derivative noise, domain-warped ridges, and five biomes on one generator
TerrainNoise.h is a 72-line header-only pure-CPU library with no GPU or engine dependencies. Every coordinate hashes deterministically via 32-bit integer wraparound (Hash2), interpolated with a C² quintic fade curve u(t) = 6t⁵ − 15t⁴ + 10t³ alongside its exact analytic derivatives du(t) = 30t⁴ − 60t³ + 30t² (ValueNoiseD).
Why compute exact derivatives during noise evaluation? Because Play2Train uses Inigo Quilez's gradient-damped noise in both of its fractal building blocks:
FbmEroded(x, z, octaves): accumulates the weighted gradient(dx, dz)across octaves (gain0.5, lacunarity2.02) and divides each octave's contribution by1.0 + 0.7 · (dx² + dz²). Steep slopes automatically damp out high-frequency chatter while flat valley floors keep fine surface texture — mimicking hydraulic smoothing before a single raindrop runs.Ridged(x, z, octaves): folds noise into sharp crests viar = (1 - |n|)², multiplies each octave by the previous octaveprevso crisp rocky detail concentrates along existing ridge spines, and damps by1.0 + 0.35 · (dx² + dz²)(lacunarity2.07).
TerrainGenerator (TerrainGenerator.cpp) hashes its 64-bit seed through a SplitMix64 avalanche into stable coordinate offsets (m_seedOffX, m_seedOffZ) in [0, ~16,384), then evaluates HeightAt(wx, wz) by blending four fields:
- A very low-frequency macro mountainousness mask (
macroFreq = 0.004, smoothstepped over[0.35, 0.58]) so one world contains both broad rolling lowlands (baseAmp = 1.5, 5 octaves ofFbmEroded) and tall alpine ranges without looking uniformly noisy. - Domain-warped ridged peaks: two independent
ValueNoiseDlookups offset the ridge sampling coordinates by up to±15units (warpFreq = 0.01,warpAmp = 30.0) before sampling 5 octaves ofRidged(ridgeFreq = 0.012), sharpened bypow(ridge, 1.3)and scaled byridgeAmp = 38.0(needed because world terrains are roughly 50× wider than tall). - Low-frequency basin carving: subtracts
carveAmp · (1 - carveRaw) · (1 + 0.6 · macro)(carveFreq = 0.015,carveAmp = 7.0) to pull lowland basins belowseaLevel = 2.0ffor natural ponds and deepen alpine valleys. - Five biomes on one deterministic generator (
TerrainBiome:Hybrid = 0,Ocean = 1,Grassland = 2,Desert = 3,Mountain = 4): instead of maintaining five incompatible terrain algorithms, focused profiles simply bias the same shared fields (Oceanbuilds a submerged archipelago with island peaks abovemacroRaw ∈ [0.58, 0.78];Grasslanddampens mountains to7%and basin carve to12%;Mountainholds ridge strength at0.65 + 0.35 · macro;Desertand dry zones inHybridlayer wind-aligned warped(½ + ½ sin)²dunes withduneFreq = 0.055,duneAmp = 2.8,duneWarpAmp = 18.0, withHybridaridity damped out of mountain cores by1 - 0.65 · mountains).
Stage 2: 60,000 hydraulic droplets and 3 thermal talus passes
Once the raw height grid exists, Engine::Erode (TerrainErosion.h/.cpp) runs two physical weathering passes in place using an explicit local SplitMix64 PRNG seeded with erosion.seed ^ params.seed (no global RNG state, never std::rand):
| Pass | Default parameters (ErosionParams) |
Exact physical rule |
|---|---|---|
Hydraulic droplet erosion (HydraulicErode) |
numDroplets = 60,000, maxLifetime = 30, erosionRadius = 3, inertia = 0.05, sedimentCapacity = 4.0, minSedimentCapacity = 0.01, erodeSpeed = 0.3, depositSpeed = 0.3, evaporateSpeed = 0.01, gravity = 4.0 |
Each droplet samples bilinear height & gradient, blends downhill direction with inertia, computes capacity = max(-Δh · speed · water · 4.0, 0.01), deposits bilinearly when uphill (min(Δh, sediment)) or over capacity ((sediment - capacity) · 0.3), or erodes via a precomputed normalized cone brush of radius 3 (min((capacity - sediment) · 0.3, -Δh)). Updates speed = sqrt(max(0, speed² - Δh · 4.0)), evaporates 1% water per step, and deposits all remaining sediment on exit so carried sediment is not discarded. |
Thermal talus erosion (ThermalErode) |
thermalIterations = 3, talusAngle = 0.6, thermalRate = 0.5 |
Double-buffered across all 4 cardinal neighbors (±x with dx, ±z with dz). Wherever hc - hn > 0.6 · cellSpacing, shifts 0.5 · 0.5 · excess from the higher cell to the lower cell, slumping unstable vertical spikes into realistic scree slopes. |
Droplet and thermal erosion transform mathematical noise into weathered slopes — but they leave a structural flaw. Because each droplet lives for at most 30 steps and stops whenever it hits a flat spot or local depression, eroded mountains end up dotted with hundreds of tiny disconnected hollows. Rainwater never travels from the highest ridge all the way to the coast. That is the exact problem Stage 3 exists to solve.
The deterministic hydrology pass: turning erosion scars into connected drainage networks
For non-technical readers, imagine standing over a sandbox sculpted into hills and pouring a watering can over the top. If the sand has dozens of small footprints and thumb-sized pits, water pools inside each little crater and stops. To discover where real rivers ought to flow, hydrologists use a clever two-step trick: first, they make a temporary photocopy of the map and mentally fill every pothole with water up to its rim — sloping the water surface downward by a hair's breadth (1 millimeter) toward the map's outer edge so every drop knows which way to escape. Next, they trace where every single square of rain flows downhill on that filled map. Where hundreds of squares all funnel into the same crease, a stream emerges; where the stream reaches flat valley ground, silt settles into a wide alluvial meadow; and right along the freshly cut stream edges, loose dirt slumps into gentle riverbanks — leaving distant mountain cliffs untouched.
Engine::ApplyHydrology (src/engine/runtime/terrain/TerrainHydrology.h/.cpp) implements that exact five-step pipeline in 200 lines of pure, order-stable C++23 with zero random number generation. Given the same input heightfield, it produces bit-identical output on every run (verified by FNV-1a float buffer hashes in unit-tests/Engine/Terrain/terrain-hydrology-test.cpp).
Let's walk through all five deterministic stages inside TerrainHydrology.cpp:
- Priority-Flood depression filling (
FillDepressions, Barnes et al.) on a routing copy. The pass copiesheightsinto a temporary routing surfacehr, pushes every border cell into a min-heap keyed by(filledHeight, cellIndex)(guaranteeing deterministic tie-breaking by index), and floods inward across all 8 neighbors. Any interior cell lower thanhr[i] + kEpsis lifted tostd::max(hr[ni], hr[i] + kEps)withkEps = 1e-3f. That tiny millimeter tilt guarantees every filled depression has a strictly downhill neighbor all the way to the map border — while leaving the original terrainhcompletely untouched so real basins and lake beds are not erased. - D8 steepest-descent flow accumulation (
ComputeFlowAccumulation). Every cell starts withflow[i] = 1.0funit of rain. Allnx × nzindices are sorted descending byhr[a] > hr[b](tie-breaking deterministically ona < b). A single linear sweep processes every upstream cell before its downstream recipient, selecting the steepest-descent neighbor among the 8 directions (slope = (hr[i] - hr[n]) / dist[k], where diagonal neighbors divide bysqrt(dx² + dz²)) and addingflow[i]directly intoflow[best]. Border cells drain off-map. - Logarithmic stream carving + valley cross-section blur + waterline floor clamp. A cell only begins carving once its accumulated upstream catchment exceeds
flowThreshold = 250.0f(~0.1 hectares at 2 m cell spacing). Above that threshold, raw incision depth grows logarithmically — because real rivers deepen slowly downstream rather than linearly into bottomless canyons:carve[i] = min(maxCarve, carveStrength * log1p(flow[i] - flowThreshold))with defaultscarveStrength = 0.28fandmaxCarve = 2.0f.- At
flow = 260, raw carve is0.67 m; atflow = 500,1.55 m; atflow = 1,000,1.85 m; and atflow = 1,514.04cells, incision cleanly saturates at the2.0 mcap. - Next,
Blur3x3runscarveBlurPasses = 2passes of a 3×3 box blur over thecarvefield, widening a harsh 1-cell trench into a smooth V/U valley cross-section. - Finally, before subtracting
carve[i]from the real terrainh[i],TerrainGenerator::GenerateHeightsclampshp.carveFloorY = std::max(hp.carveFloorY, m_p.seaLevel - 1.2f). Streams visibly incise down into the shoreline so they meet the water naturally, without ever trenching deep channels across submerged lake beds.
- Valley sedimentation (alluvial flats). Over
sedimentPasses = 2double-buffered (order-independent) iterations, any interior cell that carries substantial water (flow[i] >= 150.0f) and sits on already-gentle ground (|∇h| <= 0.10, checked via squared central differences(hx² + hz²) <= 0.01) relaxes45%(sedimentStrength = 0.45f) toward the mean of its 4 cardinal neighbors. Bumpy stream bottoms smooth out into flat alluvial valley floors. - Localized bank relaxation (talus near streams only). Carving a stream creates steep fresh cut-banks. Rather than running global thermal erosion again (which would soften distant alpine cliffs),
ApplyHydrologyrunsbankIterations = 3double-buffered thermal-talus passes (bankTalus = 0.50f,bankRate = 0.30f) gated strictly byif (carve[i] <= 0.01f) continue;. Only freshly carved stream banks slump to a stable angle; every cliff and peak outside the drainage corridor stays crisp.
// src/engine/runtime/terrain/TerrainHydrology.cpp
// ---- Stream carving ----
std::vector<float> carve(N, 0.0f);
for (size_t i = 0; i < N; ++i) {
const float excess = flow[i] - p.flowThreshold;
if (excess > 0.0f)
carve[i] = std::min(p.maxCarve, p.carveStrength * std::log1p(excess));
}
Blur3x3(carve, nx, nz, p.carveBlurPasses);
for (size_t i = 0; i < N; ++i) {
if (carve[i] <= 0.0f) continue;
const float floorRoom = h[i] - p.carveFloorY;
if (floorRoom <= 0.0f) continue; // already at/below the floor
h[i] -= std::min(carve[i], floorRoom);
}Geomorphology-aware material weights (TerrainGenerator::GenerateWeights)
Before seeding the 3D volume, GenerateWeights computes the initial 4-layer material blend (grass, sand, rock, implicit snow) for every column — and it deliberately avoids ugly horizontal contour stripes. Alongside central-difference slope (1 - ny) and altitude above seaLevel, it evaluates two real-world geomorphological cues:
- Topographic position against an ~8 m ring (
kx = max(1, round(8 / dx))):(h[i] - ringMean) / ringDistanceis positive on exposed crests and plateau lips, and negative inside gullies and hollows. Scaled bysnowBand = max(snowHi - snowLo, 1e-3)(default3.0 m), effectivesnowAltitudeis boosted in sheltered hollows (-1.2 × snowBand × positionwhenposition < 0) and scoured off exposed ridges (-0.5 × snowBand × positionwhenposition > 0), while sharp highland crests add bare rock (+(1 - rock) · 0.7 · highland · SmoothStep(0.4, 0.8, position)). - Poleward aspect (
dhdz * ny): slopes facing the fixed shaded poleward direction (-Z) hold snow lower down the mountain (+0.6 × snowBand × poleward), whileFbmErodedperturbations break up the snowline, rock-slope threshold, and shoreline sand band.
Every biome then biases the exact same 4-way partition (grass + sand + rock + snow == 1), which TerrainVolumeData::SetMaterialGrid quantizes via largest-remainder into the 3-byte TerrainMaterialWeights column.
Meshing the volume with Surface Nets and keeping materials intact
Now that we have a 3D grid of (density, grass, sand, rock) samples — possibly carved with tunnels and overhangs — how does Play2Train turn those numbers into triangles the GPU and physics engine can use?
For non-technical readers, imagine a 3D jungle gym of tiny cubes covering the landscape. Some cubes are completely buried underground (all 8 corners solid); some float in empty air (all 8 corners empty); and only a thin skin of boundary cubes straddles the solid-to-air transition. The classic algorithm (Marching Cubes) consults a 256-entry lookup table to stamp miniature triangle templates inside each boundary cube — often producing sliver triangles and tricky lookup seams. Surface Nets takes the dual approach: it places just one vertex inside each boundary cube, parked at the average position of all edges where solid meets air, and then weaves a clean quad (two triangles) connecting the four cubes around every grid edge that crosses from rock into air. The result looks like an elastic fishing net pulled smoothly over the clay.
Inside TerrainVolumeData::BuildChunkMesh(std::uint64_t key) (TerrainVolumeData.cpp), the volume is partitioned into 64 × 64 × 64 cell chunks (kChunkSizeXZ = 64, kChunkSizeY = 64), addressed by 21-bit packed 64-bit keys (EncodeChunkKey / EncodeCell, supporting grids up to 2²¹ = 2,097,152 per axis). Four concrete details make the mesher rock-solid:
- One dual vertex per active cell (
vertexForCell). For every cell with at least one solid (>= 128) and one empty (< 128) corner, the mesher walks all 12 cube edges (kEdges). On each sign-changing edge(a, b), it linearly interpolates the crossing point att = (128 - dA) / (dB - dA)and averages all crossings to place the dual vertex. The vertex shading normal comes from the 8-corner finite-difference density gradient(-Δx/dx, -Δy/dy, -Δz/dz), normalized with an upward fallback if degenerate. Each emitted vertex packs 11 floats:pos(3), weights RGB(3), uv(2), normal(3). - Material blend preservation instead of winner-take-all voting. Notice a subtle trap in volumetric terrain: if a cell simply picks the dominant material among its 8 corners, smooth procedural grass-to-rock transitions collapse into blocky voxel staircases, and painted brushes jitter. Instead, Play2Train lets every crossed edge inherit the full 3-byte material blend of its solid endpoint (
kCorners[solidA ? a : b]) and averages those blends across all crossings (materialSum / (255.0f * intersections)). Smooth transitions and painted boundaries survive meshing intact. - Topological edge-sign quad orientation — never shading normals. For each interior cell
(x, y, z), the mesher checks the three lattice edges bordering its far corner (+X,+Y,+Z) and emits a quad joining the four surrounding cells whenever an edge crosseskIsoDensity. Crucially, winding order (swap(q[1], q[3])) is decided strictly by whether the lower endpoint of that crossed edge is solid or empty — never by checking the dot product against the averaged shading normal. Why? Asunit-tests/Engine/Terrain/terrain-volume-mesh-test.cpprecords from real regression testing, orienting quads by averaged shading normals reversed 16–45 shared edges per seed along sharp ridges where the 8-corner gradient leaned across the crest! With edge-density-sign winding, the test suite verifies zero inconsistent shared edges across 20 rough random seeds, multi-chunk generated worlds spanning chunk seams, and exact positive/negative signed volumes on closed solid islands and hollow cavities. - Two-cell dirty halo across chunk seams (
MarkDirtySamples). Because a single modified sample can alter dual vertices in cells up to1behind it and shared quads owned by cells up to2behind it, editing any sample bounding box[min, max]expands the dirty cell range to[min - 2, max]before marking affected64³chunks dirty (ConsumeDirtyChunks()returns sorted keys deterministically).
Volumetric brushes, exact reverse-replay undo, and upward-triangle surface indexing
Because the underlying truth is the 3D density + material field, editing tools and runtime queries operate cleanly on the volume without brittle mesh surgery:
| Operation | Exact implementation (TerrainVolumeData.cpp / TerrainSurfaceData.h) |
Engineering invariant |
|---|---|---|
DigEllipsoid |
Subtracts max(1, round(255 · amount01 · falloff(d²))) from density across 4 falloff kernels (0: (1−d²)², 1: 1−d, 2: hard 1, 3: exp(−4d²)), leaving underlying materials intact |
Radii clamp up to at least (dx, dy, dz) so even the smallest UI brush always reaches a sample |
PlaceEllipsoid |
Marks every 8-corner cell whose center lies inside the ellipsoid to density = 255 and TerrainMaterialWeights::Layer(material) |
Adds complete unit cells (not fractional height increments); sub-cell brushes fall back to placing their containing cell |
PaintEllipsoid |
Writes Layer(material) only to solid samples (density >= 128) inside the ellipsoid |
Never changes terrain geometry or contaminates air samples |
ApplyChanges (Undo/Redo) |
Validates every SampleChange index and material sum before mutating; Redo walks forward, Undo walks rbegin() → rend() |
PlaceEllipsoid writes shared cell corners multiple times; reverse replay guarantees the very first pre-edit density and blend are restored |
RaycastLocal |
Clips ray to volume AABB, marches at quarter-cell step along axes the ray actually crosses (step = max(1e-4, cellCrossingT · 0.25)), then runs 16 iterations of binary bisection on trilinear >= 128 sign flip |
Adaptive stepping avoids ~25× redundant evaluations on vertical rays over wide terrain; 16-step bisection resolves hits to 2⁻¹⁶ of a step inside caves and overhangs |
TerrainSurfaceData |
Bins all actual rendered triangles with upward face normal (face.y > 1e-10f) into an (nx-1) × (nz-1) XZ grid; provides SampleTop(x, z) (exact barycentric highest upward triangle + weights) and HeightUpperBound(x, z, radius) |
Density-column scanning bridges dug holes and misses Surface Nets averaging; filtering face.y > 1e-10f ensures a cave ceiling never becomes a placement floor for grass, trees, or spawned characters |
On top of TerrainSurfaceData, TerrainAO.h bakes world-space horizon-based ambient occlusion (ComputeHeightfieldAO): from each grid cell, it marches outward in 8 compass directions × 16 steps using true world-space (dx, dz) spacing, records the steepest sky-blocking horizon angle atan(maxSlope) · (2 / π), and darkens crevices, gullies, and cliff bases while leaving open ridges bright. Meanwhile, TerrainLayers.h defines the engine's material layer textures (grass.png, sand.png, stone.png, snow.png, plus forest, grasstall, ocean, oceandeep, path) paired with per-texture metric relief depths (0.020 m for grass blades, 0.012 m for sand ripples, 0.150 m for stone joints, 0.050 m for wind-packed snow).
Storing worlds without vertex dumps: the P2TTRN v4 binary format
When a player saves an edited terrain — complete with carved tunnels, painted roads, and hydrological valleys — what should actually go to disk?
For non-technical readers, imagine mailing a Lego castle to a friend. You could ship the giant pre-assembled castle in a fragile crate (a vertex dump: tens of megabytes of raw triangles, normals, collision trees, and baked shadows that break the moment you want to edit a brick). Or you could mail a compact instruction sheet: "65 layers of solid rock, 2 transition bricks, 62 layers of empty sky." That is run-length encoding (RLE) over a vertical column. Because almost every vertical column in a terrain volume consists of solid earth below and open air above, 129 samples collapse into 3 or 4 tiny 8-byte notes.
Play2Train's P2TTRN v4 specification (TerrainFormat.md) and serializer (src/game/systems/TerrainPersistence.h/.cpp) store only the scalar density field, normalized material blends, grid geometry, and four lightweight appearance settings — never meshes, never collision BVHs, never AO textures, and never scatter instances.
Exact 76-byte header and 8-byte run stream (TerrainFormat.md)
Every .terrain.p2t sidecar is raw little-endian binary (IEEE-754 float32) with zero struct padding:
| Offset | Field | Type | Notes |
|---|---|---|---|
0 |
Magic P2TTRN\0\0 |
8 bytes |
Exact match required |
8 |
Schema version | uint32 |
Must equal 4; versions 1–3 rejected outright without migration |
12 |
Sample dimensions nx, ny, nz |
3 × uint32 |
Each in [2, 2²¹]; product <= 64 × 1024 × 1024 (67,108,864 samples) |
24 |
Local sample spacing dx, dy, dz |
3 × float32 |
Finite and strictly > 0 |
36 |
Local grid origin x0, y0, z0 |
3 × float32 |
Finite |
48 |
Terrain/biome type | int32 |
0 Hybrid, 1 Ocean, 2 Grassland, 3 Desert, 4 Mountain |
52 |
Procedural presentation enabled | uint32 |
Strictly 0 or 1 (decorated > 1 is rejected) |
56 |
Scatter seed | uint64 |
Rebuilds deterministic foliage/rock placement on load |
64 |
Sea level (world Y) | float32 |
Finite |
68 |
Snow threshold (snowHi, above sea level) |
float32 |
Finite |
72 |
Run count (runCount) |
uint32 |
Must satisfy 1 <= runCount <= nx * ny * nz |
Immediately following byte 75 come runCount packed 8-byte Run records (static_assert(sizeof(Run) == 8)):
// src/game/systems/TerrainPersistence.cpp
struct Run {
std::uint32_t count = 0; // repeated consecutive samples
std::uint8_t density = 0; // UNORM8 scalar density (iso = 128)
Engine::TerrainMaterialWeights material; // 3 bytes: grass, sand, rock (snow implicit)
};
static_assert(sizeof(Run) == 8);Run the numbers on a full 513 × 129 × 513 production terrain (33,948,801 samples):
- Uncompressed 4-byte volume:
33,948,801 × 4 = 129.50 MiB. - Y-fast RLE stream (
P2TTRN v4): each of the263,169vertical columns runs solid255from bedrock up to the surface, passes through1–2unsaturated127/dytransition samples, and runs0to the top of the volume — 3 to 4 runs per column (76 + 263,169 × {3,4} × 8bytes), landing at6.02–8.03 MiB, a16.1×–21.5×size reduction with zero loss of the quantized density field or material blends (and often even smaller when consecutive columns share identical top/bottom states).
Fail-closed load checks and deterministic rebuilds
ReadCurrent in TerrainPersistence.cpp treats every file on disk as untrusted input:
- No legacy shims. Anything other than exact
P2TTRN\0\0magic andversion == 4fails immediately with a descriptive error string. - Zip-bomb protection.
kMaximumSamples = 64 × 1024 × 1024(67,108,864samples, capping raw allocation at256 MiB) gives comfortable headroom above513 × 129 × 513while stopping a tiny forged RLE file from triggering multi-gigabyte allocations. - Exact payload verification. Before allocating or decoding a single run, the loader seeks to EOF and verifies
payloadBytes == runCount * 8— rejecting both truncated files and files with trailing garbage bytes. - Per-run validation and atomic commit. Every run must satisfy
count > 0,material.IsValid()(grass + sand + rock <= 255), andcount <= sampleCount - decoded; total decoded samples must equalnx * ny * nzexactly. Everything parses into a localTerrainData parsedand only moves into the caller'sdataon the final line — so a failed read never leaves half-loaded terrain in memory. - Derived presentation rebuilt from rendered triangles. On successful load, the engine rebuilds the
64³Surface Nets render chunks and collision meshes, buildsTerrainSurfaceDatafrom the upward-facing triangles, and regenerates horizon AO, terrain/water height textures, and deterministic scatter from those triangles. If the header'sdecoratedflag is0, any stale presentation resources left over from a previously loaded world are explicitly cleared.
Honest boundaries and where the system stops
Play2Train's terrain pipeline makes clear, deliberate trade-offs rather than trying to be every kind of voxel engine at once:
- Strict height-seeding range.
InitializeFromHeightsandSetHeightSubRegionrefuse any height outside[y0, y0 + (ny - 2) * dy](default[-64, +63]in local Y) rather than clipping peaks flat. Worlds that need taller seeded relief must increasenyordyexplicitly before seeding (arbitrary caves and overhangs inside[0, ny - 1]remain fully supported viaImportand brushes). - Hydrology runs once on the pre-volume heightfield. Domain-warped generation, hydraulic/thermal erosion, and D8 hydrology all operate on the 2D height grid before seeding the 3D density volume. If a player later digs a cavern or trenches through a ridge with
DigEllipsoid, the terrain updates its64³Surface Nets chunks and collision live — it does not re-run watershed hydrology or simulate dynamic underground river physics. - Single-layer painting vs. four-way procedural blends. Procedural generation writes smooth 4-channel largest-remainder blends (
TerrainMaterialWeights::FromFloats), and Surface Nets, undo/redo, andP2TTRN v4preserve arbitrary 4-way blends faithfully. The interactivePaintEllipsoidandPlaceEllipsoidbrushes currently stamp a single pure layer (Layer(material)=255on one channel) onto touched samples rather than soft-blending partial paint opacity. - Bounded single-volume storage, not infinite streaming.
P2TTRN v4stores one bounded terrain volume per.terrain.p2tsidecar (capped at64 × 1024 × 1024samples) and rejects versions 1–3 without migration code. It is designed for rich, editable handcrafted/procedural world maps rather than infinite Minecraft-style chunk streaming. - Smooth Surface Nets vs. sharp-corner Dual Contouring. Surface Nets averages edge crossings without solving Quadratic Error Functions (QEF) over Hermite normals. That keeps chunk meshing simple, fast, and organically smooth for hills, riverbeds, and caves — at the trade-off that razor-sharp 90° architectural corners round off slightly, and saddle edges can join four faces (or three at an open grid rim), explicitly checked as balanced edge pairs in
terrain-volume-mesh-test.cpp. - Clean SDK vs. game boundary. Pure-CPU noise, generation, erosion, hydrology, volume data, Surface Nets meshing, surface indexing, normals, and horizon AO live in the reusable
Play2TrainSDK (src/engine/runtime/terrain/), whereas.terrain.p2tsidecar persistence (TerrainPersistence.{h,cpp}), editor undo stacks, and chunk entity orchestration live on the game side (HavenCity).
Sources and further reading
- Sarah F. Frisken (Gibson), "Constrained Elastic Surface Nets: Generating Smooth Surfaces from Binary Segmented Data" (MICCAI 1998) — original Surface Nets dual-vertex formulation.
- Richard Barnes, Clarence Lehman, and David Mulla, "Priority-Flood: An Optimal Depression-Filling and Watershed-Labeling Algorithm for Digital Elevation Models" (Computers & Geosciences, 2014) — the border-seeded priority-flood algorithm with epsilon slope used in
FillDepressions. - John F. O'Callaghan and David M. Mark, "The Extraction of Drainage Networks from Digital Elevation Data" (Computer Vision, Graphics, and Image Processing, 1984) — foundational D8 steepest-descent flow accumulation method.
- Inigo Quilez, "Value Noise Derivatives" — analytic quintic value noise derivatives and gradient-damped ("eroded") fBm that inspired
TerrainNoise.h. - Hans Theobald Beyer, "Implementation of a Method for Hydraulic Erosion" (Bachelor's thesis, Technische Universität München, 2015) — canonical particle-droplet hydraulic erosion formulation adapted in
TerrainErosion.cpp. - Play2Train internal source files (closed-source SDK, architecture snapshot December 2026):
TerrainFormat.md,src/engine/runtime/terrain/TerrainVolumeData.h/.cpp,TerrainMaterialWeights.h,TerrainNoise.h,TerrainGenerator.h/.cpp,TerrainErosion.h/.cpp,TerrainHydrology.h/.cpp,TerrainSurfaceData.h,TerrainNormals.h,TerrainAO.h,TerrainLayers.h/.cpp,src/engine/components/TerrainVolume.h,src/game/systems/TerrainPersistence.h/.cpp, andunit-tests/Engine/Terrain/terrain-{ao,erosion,generator,hydrology,noise,normals,persistence,volume-mesh}-test.cpp. - Related Play2Train architecture articles on Gattic: One Render Graph, Two Backends, Unchanged Shaders in Play2Train, GPU Ray Tracing Against Skinned Characters Without RTX in Play2Train, and Seamless Portals and a GL-Free Budgeted View Scheduler in Play2Train.