Worlds from a seed

Every map is generated from a zone id and a 32-bit seed, byte-identical on server and browser, so no tile ever crosses the wire.

A hero in a sandstone ruin in the Scorched Dunes, the desert stretching away behind
Contents
  1. Why not send the map
  2. A seeded RNG, forked by purpose
  3. Four generators, one contract
  4. Props that can't block the way
  5. A nav grid both sides share
  6. Testing determinism and connectivity
  7. The budget
  8. What the seed doesn't cover
  9. Read next

A zone is up to 176 × 176 tiles, over a thousand props, up to a couple of hundred lights and 68 spawn points. None of it goes over the network: the server sends a zone id and one uint32, and the browser builds the same map bit for bit.

A diagram: the matchmaker's zone id and room id go through seedFor into one uint32; the server's World and the client's session both call generateZoneFor with it and get the same ZoneMap
The whole contract. Four bytes of seed replace what would otherwise be hundreds of kilobytes of map on every zone change.

Why not send the map

  • Size. Tiles, variants and heights for a 176 × 176 wilderness are ~186 KB before props, which are thousands more records. Every zone change would stall on a download.
  • The client needs it anyway. Movement prediction collides against the same walls as the server, click-to-move pathfinds locally, and the minimap reads the same tiles.

The price is discipline: procgen must be pure. No Math.random, no Date.now, no unspecified iteration order, no engine-dependent float shortcuts. shared/procgen and shared/nav have no DOM and no node:* imports; both sides import the same modules.

A seeded RNG, forked by purpose

sfc32, seeded through a string hash so seeds can be built from readable labels:

shared/rng.tsTypeScript
/** 32-bit string/number hash (FNV-1a variant, then avalanche). */
export function hash32(...parts: Array<string | number>): number {
  let h = 0x811c9dc5
  for (const part of parts) {
    const s = typeof part === 'number' ? String(part) : part
    for (let i = 0; i < s.length; i++) {
      h ^= s.charCodeAt(i)
      h = Math.imul(h, 0x01000193)
    }
    h ^= 0x7c // separator so hash32('ab','c') !== hash32('a','bc')
    h = Math.imul(h, 0x01000193)
  }
  h ^= h >>> 16
  h = Math.imul(h, 0x85ebca6b)
  h ^= h >>> 13
  h = Math.imul(h, 0xc2b2ae35)
  h ^= h >>> 16
  return h >>> 0
}
 
export class Rng {
  /** Derive an independent child stream (e.g. per-room, per-feature). */
  fork(label: string | number): Rng {
    return new Rng(hash32(this.nextU32(), label))
  }
  // nextU32, next, range, int, chance, pick, shuffle…
}
  • Math.imul and >>> 0 keep everything in 32-bit integers: no floats to disagree about.
  • The MurmurHash3 finalizer spreads near-identical inputs like a1_crypt_of_ash_1 and _2.
  • fork gives each stage its own stream ('rooms', 'props', 'spawns'). One extra random call in the room stage changes only rooms, not every chest downstream.

Seeds come from the room:

shared/world/zoneInput.tsTypeScript
export function seedFor(zoneId: string, roomId: string): number {
  return zoneId.endsWith('_town') ? hash32(zoneId) : hash32(zoneId, roomId)
}

Towns are always the same town, so players learn where the stash is. Everything else mixes in the Colyseus room id: two parties get two crypts, and a disposed-and-recreated room is a new crypt. The seed rides the schema as a uint32 in the first patch.

Four generators, one contract

shared/procgen/index.tsTypeScript
// Public procgen API. generateZone is PURE + DETERMINISTIC: same input → byte-identical output.
export function generateZone(input: ZoneGenInput): ZoneMap {
  switch (input.kind) {
    case 'town':
      return generateTown(input)
    case 'wilderness':
      return input.biome === 'shattered_isles' || input.biome === 'astral_garden' ? generateIsles(input) : generateWilderness(input)
    case 'dungeon':
      return generateDungeon(input)
  }
}
Generator How
Town hand-authored 64 × 64 template per act, seeded decoration jitter, shared kit for gates, wall torches, NPC spots
Wilderness key points (exits, waypoint, clearings) → MST plus a few loop edges → midpoint-displaced trails → noise-carved ground bounded by cliffs or tree walls → roads, ponds, bridges, dressing, spawns. 1,924 lines
Dungeon rectangles or cellular-automata caves, MST corridors plus ~15% loops, modular walls; boss room = farthest walk from entrance. Mirror Halls (symmetric) and Gloam Heart (spiral) use fixed layouts
Isles Poisson-scattered noisy blobs over a starfield, MST chain bridges, unreachable islands pruned (Shattered Isles, Astral Garden)
Three generated maps side by side: a desert wilderness with winding trails, floating islands joined by bridges over a starfield, and a symmetric hall of mirrors
Three generators from the preview tool: the Scorched Dunes (wilderness), the Shattered Isles (islands), and the Mirror Halls (a fixed symmetric dungeon layout). Red dots are monster packs, orange are champions, cyan squares are exits, the blue disc is the waypoint and the white line is an A* path from the entrance through every exit.
The same crypt dungeon generated with three different seeds, each a different arrangement of rooms and corridors
One dungeon definition, three seeds. Pale rims are modular walls, small yellow points are wall torches.

Wilderness and dungeons also BFS every tile's walking distance from the entrance. Spawns use it to keep packs off the entrance and weight them toward the far end, stored as depth in 0..1. Because it's walking distance, a loop-corridor shortcut counts as close.

Props that can't block the way

The classic procgen bug is a barrel sealing the only corridor. Instead of generate-test-repair, every blocking prop goes through a Placer that only accepts placements that keep connectivity:

shared/procgen/placer.tsTypeScript
// Connectivity-safe prop placement.
//
// Blocking props are rasterized with the same footprint rule as NavGrid. Nav is 8-dir with no
// corner cutting, whose reachability equals 4-connectivity, so blocking a set of tiles is safe iff
// all walkable 4-neighbours of that set stay mutually connected. Checked in increasing cost: the
// local 3×3 simple-point test (single tiles), a BFS confined to a window around the footprint,
// then (multi-tile footprints only) a full-grid BFS. Every accepted placement preserves global
// connectivity by construction, so generators never have to repair maps afterwards.

The first check is digital topology: a tile is a simple point if its walkable orthogonal neighbours all fall in one run around its 8-ring, so blocking it disconnects nothing.

Four 3×3 neighbourhoods: open floor and a corner can be blocked locally, while a one-tile corridor and a gap between two pillars need a wider search
The local test in four cases. It only ever answers yes; a no hands the question to a breadth-first search in a window around the prop.
  • Most placements are single tiles on open ground and pass in a few dozen instructions.
  • The rest get a windowed BFS; multi-tile footprints get a final full-grid BFS.
  • The footprint rule matches the nav grid exactly (blocked if the tile center is strictly inside the prop's shape), so they can't disagree.
  • Paths, exit approaches, the waypoint disk and NPC spots are reserved before decorating.

A nav grid both sides share

NavGrid.fromZone builds two byte layers: walk and sight. Water and chasms block walking, not arrows; towers block both.

  • A*: 8-directional, no corner cutting, octile heuristic, indexed binary heap, zero per-node allocation. A node budget returns a partial path; a line-of-sight pass pulls the string.
  • Line of sight: grid DDA (Amanatides and Woo). Exact corner crossings need both side tiles clear.
  • walkableSegment: center line plus two rails offset by agent radius.
  • Distance fields: bounded Dijkstra from one tile.

150 monsters chasing 40 players can't each run A* whenever a target moves. Three tiers:

server/game/sim/ai.tsTypeScript
/** Move toward `t` until within `stopAt`. Direct steering when the line is clear, else the shared
 *  distance field toward that player (one Dijkstra per target shared by the whole crowd), else A*. */
function approach(w: World, m: SimMonster, t: Unit, dtMs: number, stopAt: number): void {
  // …
  const direct = d < 12 && walkableSegment(w.nav, m, { x: gx, y: gy }, 0.2)
  if (direct) { /* steer straight at the target */ return }
  if (t.kind === 'player') {
    const f = w.fieldFor(t)
    const dir = f ? f.direction(m.x, m.y) : null
    if (dir && (dir.x !== 0 || dir.y !== 0)) { /* follow the field downhill */ return }
  }
  if (m.path.length === 0 || now >= m.nextPathAt) {
    m.nextPathAt = now + 700 + w.rng.int(0, 300)
    if (!w.budgetPath()) return
    pathTo(w, m, t.x, t.y, 1500)
  }
  // …
}
  1. Direct: target within 12 tiles, clear line: walk at it.
  2. Shared field: one field per chased player, rebuilt on tile change at most 4×/s, flooding 40 tiles.
  3. A*: capped at 10 searches per room per tick, with jittered repath timers.
Nav operation (test suite, this machine) Time
A* path (507 nodes expanded) 0.067 ms
Distance field build 0.042 ms
Nav grid, largest zone < 1 ms

The client predicts on the same grid, so its position and the server's almost always agree. See Twenty ticks a second.

Testing determinism and connectivity

Every sample input is generated twice at three seeds and compared byte for byte; two different seeds must differ (except towns):

shared/procgen/procgen.test.tsTypeScript
describe('determinism', () => {
  for (const input of SAMPLE_INPUTS) {
    test(input.id, () => {
      for (const seed of [1, 42, 0xdeadbeef]) {
        const a = generateZone({ ...input, seed })
        const b = generateZone({ ...input, seed })
        expect(Buffer.from(a.tiles).equals(Buffer.from(b.tiles))).toBe(true)
        expect(Buffer.from(a.variant).equals(Buffer.from(b.variant))).toBe(true)
        expect(a.props).toEqual(b.props)
        expect(snapshot(a)).toBe(snapshot(b))
      }
      // …
    })
  }
})

validateZone runs over 50 seeds per sample: from a walkable start, a 4-connected BFS must reach every exit, arrival point, the waypoint, every NPC, every interactive prop, the boss spawn and every region center. A second suite does it for every biome at several depths and sizes.

scripts/procgen-preview.ts renders any sample and seed to PNG with A* paths to every exit. Every map image in this post came from it.

The budget

50 ms for the largest maps. A room generates synchronously in the World constructor, on the thread every room shares; the client pays it behind a loading screen.

Medians of nine seeds on a busy dev machine:

Zone Kind Size Generate Nav grid Props Lights
Hollowmere (Act I town) town 64 × 64 2.0 ms 0.09 ms 500 74
Crypt of Ash, level 1 dungeon 104 × 104 1.6 ms 0.04 ms 364 147
Drowned Cathedral, level 1 dungeon 120 × 120 5.9 ms 0.15 ms 461 212
Mirror Halls, level 1 dungeon 120 × 120 3.1 ms 0.27 ms 343 130
Blighted Fields wilderness 144 × 144 29.5 ms 0.26 ms 973 38
Shattered Isles islands 176 × 176 23.7 ms 0.12 ms 544 20
Scorched Dunes wilderness 170 × 170 48.8 ms 0.26 ms 1,260 9
River of Flame wilderness 176 × 176 52.7 ms 0.31 ms 1,328 144

Dungeons are mostly void and cheap. Big wildernesses (noise per tile, trails, 1,000+ Placer calls) sit at the 50 ms line when loaded, under it when idle; the perf test uses a median of five. Next step if they grow: cache maps by (zoneId, seed) on the server.

A hero in the Mirror Halls: pale pillars and glowing orbs inside violet walls, floating over a starfield
The Mirror Halls in the engine, captured fresh from a local server. The client built this from a zone id and four bytes of seed.

What the seed doesn't cover

Combat, loot and AI use a separate clock-seeded RNG per room and are server-only; the client never predicts a drop or crit. Spawn points come from the map; which monsters, affixes and packs appear is server state.

The rule for the whole codebase: derivable from zone id and seed → derived on both sides. Depends on what players do → server, then sent.