Malsimulation · internals · a descent in six layers

How the world actually works

One illustrated page, from why the simulation exists down to how a tick is counted and a hash is frozen. Each layer is a level of the island. The sky holds the intent. The surface holds the world and the lives on it. The deeper you dig, the closer you get to the machine.

Snapshot generated 2026-10-03 from dfdbbef version 0.3.0-dev Regenerated only on request: the code may have moved since. Amended 2026-10-04: the population model and decision loops. The 2026-10-07 agency deep dive and 2026-10-08 decision-core deep dive have their own source stamps on Deep dives.

  1. 0 · Sky Why it exists, and how intent becomes code
  2. 1 · Surface The island: lattice, generation, water, cost
  3. 2 · Life Bodies, needs, goods, the generated past and agency
  4. 3 · Caverns The engine: ticks, one queue, the facade, saves
  5. 4 · Tunnels Modules, walls, memory, threads, decisions
  6. 5 · Bedrock Determinism, RNG, A*, shaders, tests
A cross-section of the island used as this page's map: sky, surface and village, caverns, tunnels and bedrock xoshiro256++ · forkSeed(seed, "sim") · (tick, seq) · 0x584d5fc099546a3c · 8,640,000 ticks a day · 0x3ba7802c37fed0bc · SPIR-V · MSL · DXIL866 = ⌊1000·√3/2⌋ · 3r²+3r+1 · A* (f, −g, id) · 30 test shards · arena per lifetime · 0x53175d61490b23df 0 · SKYintent and the record 1 · SURFACEthe island and its making 2 · LIFEpeople, beasts, goods 3 · CAVERNSthe engine 4 · TUNNELSarchitecture 5 · BEDROCKthe bits
The page's map. Select a layer to descend to it. The dashed line is the route this page takes, from a cave mouth on the hill down to the bedrock.
197,056lines of Zig
150source files in 7 modules
1,931tests
133specs, 001–163
12architecture decisions
58research notes
1,500commits since 2009
1,944,263events in one simulated week

Layer 0 · Sky

A world connected by causes

Malsimulation is a detailed simulation of a living fantasy world, and a game about understanding, influencing and inhabiting it. It reaches from the landscape and its ecology to individual lives, and outward through families, households and villages. Humans, elves, dwarves and goblins share one consequential world. It began in 2007 as a personal project, and market demand still does not set its direction.

The constitution

Nine principles

The vision's principles are the test every feature answers to. The long arc turns them into directions; the roadmap picks among those; specs make one of them true.

01

A broad world, connected by causes

Detail earns its place by explaining something, changing a choice or connecting systems.

02

Research informs reality

Models draw on evidence for the people, place and period. Simplifications are stated, never hidden.

03

Fantasy has consequences

Different bodies and lifespans matter to food, care, learning and settlement. A goblin litter is four lives.

04

Ordinary lives matter

Care, work and continuity are the game. Recovery and quiet achievement count as much as catastrophe.

05

Interest grows from rules

Failure and extinction stand. No hidden rescue, no manufactured drama.

06

The world is open to investigation

History, inspection and observation let the player test explanations. AI tellers must separate fact from interpretation.

07

Every simulated fact can be found

Whatever the world keeps can be opened and followed. A part is unfinished until it can be explored.

08

History is reproducible

Same version, same start, same interventions: same history. Rewind and branching build on that.

09

Agency belongs within the world

From watching, through influence and intervention, to living as one existing person.

The written record

From intent to code, and back

Every document owns one thing and explicitly not another. Intent flows down the ladder; measured reality flows back up as backlog items. Nothing disappears: a spec's text is never edited, only amended with a date, and a dropped idea keeps its reason.

The record as a ladder: vision, long arc, roadmap, backlog, research, spec, code, current handbook, observations INTENT CONTRACT REALITY Vision Long arc Roadmap Backlog Research Spec Code (pull request) Current handbook Observations FINDINGS RETURN Purpose, inspirations and the nine principles: the constitution.Not: features, schedules or numeric contracts. Future experiences, and what today's design must leave possible.Not: priority, deadlines or approval. Epics by category, priority tier and t-shirt size; which are designed.Not: a complete behaviour contract. Candidates, defects and deferrals, each with its provenance.Not: approval merely because an item exists. Sources, findings and labelled assumptions, cited by finding id.Not: implemented or calibrated behaviour. The contract: scope, behaviour, determinism duties, acceptance commands, then evidence.Approved specs reach main before any code; fixes arrive as dated amendments. The behaviour itself, merged after the evidence is in the spec.Floor: zig build test and the module-boundary guard. What the running system does, updated in the same change as the code.Not: unmeasured outcomes. What happened in measured runs: version, seeds, confidence, a recheck trigger.Defects and findings go back to the backlog (rule 7: say what you did not do).
The spec lifecycle inside the "Spec" rung runs draft → approved → implemented → verified, and back to draft when reality disagrees. "Reserved" holds a number with an approved outline.

The strict lane: the simulation

  • Zig source, shaders, assets/, the build and its tests.
  • New intent earns a spec, approved before any code and pushed to main first.
  • Implementation waits on a pull request whose body carries the evidence.
  • The floor is the full suite and the boundary guard; goldens that move must say why.

The light lane: the website and documentation

  • The landing page, the roadmap and internals pages, docs that describe rather than change.
  • No spec, no pull request, no Zig test run (Paweł, 2026-10-03).
  • Their own checks are the floor: site:check and the roadmap validator.
  • Straight to main, which the server publishes within five minutes. This page lives here.

Seventeen years

Every month since the first commit

One cell per month, shaded by commits. The Python years fade into a long quiet; then a single late-August day rewrites the whole thing, and September 2026 alone has more commits than the entire Python era.

The ideaA personal project; no surviving history before 2009.
Python, pyglet, caves338 commits. 2010-05-17: "finally simulation is fully deterministic".
The long quiet77 commits in fourteen years; none at all in five of them.
The rewriteZig, SDL3 and SDL_GPU. Master plan at 11:31, the Python tree removed at 00:44: 43 specs, M0–M8.
The burst845 commits: animals, production, history, population, monsters, dragons.
A windowThe public site, the unlisted roadmap, and this page.

Since the rewrite

Commits, day by day

The last 75 days. The rewrite fills the first two; the quiet in mid-September is the population batches under review, not a pause in intent.

The epics

The roadmap at a glance

44 epics: 26 closed and 18 open, in five categories. Priority is a tier, not a queue position: 3 open epics at P0, the floor nothing above is safe without; 3 at P1; 7 at P2; 5 at P3. Design runs ahead of building: 1 open epic is fully designed and 2 partly.

Specs

Every spec, by number

133 specs; numbers are never reused. The rewrite used decade bands (00x foundations, 01x core, 02x worldgen, 03x simulation …); since 073 they are simply sequential. Shade is the lifecycle stage: the darker, the further along. Hover a cell for its title.

095 is a deliberate gap. It was written as a fix for the "blue sides of the world", then folded back into an amendment on archived spec 040. That episode made the rule: a fix belongs to the spec it fixes.

295 dated amendments sit under "Amendments" headings. Spec 140, the generated history, carries the most: 40.

Negative results are kept. Spec 086 is "verified … not implemented: the premise was wrong". Specs 104 and 106 ship their mechanisms switched off because the measurement said so.

Approval is recorded in the approver's words, from "Approve as drafted" to "Zatwierdzam".

Layer 1 · Surface

An island on a hexagonal lattice

The world is one hexagonal region made of hexagonal fields. At the defaults, map size 6 with fields 100 metres across, that is 197,377 surface fields about 51 km from corner to corner, and 320,897 fields in all once the three cavern layers and the tunnel web are counted. Everything in it is generated from one seed, deterministically, before the first creature moves.

Coordinates

The lattice, and the order it is walked in

Positions are integers. A field's six neighbours are one axial step away; world positions derive from axial ones. Fields are created centre first, ring by ring, and that spiral order is load-bearing: field ids, random draws and mesh vertices all follow it.

A field and its six neighbours, with axial deltas (q, r)one field N (+1, +1) NE (0, +1) SE (−1, 0) S (−1, −1) SW (0, −1) NW (+1, 0) Axial is canonical x = 866 · (r − q) y = 500 · (q + r) 1,000 lattice units per step; metres = units × field size ÷ 1,000 Why 866? ⌊1000 · √3 / 2⌋, truncated so world ↔ axial round-trips exactly in integers. North is (+1, +1) Inherited from the 2007 Python; the (1, −1) diagonal is not a step.
Spiral order: the centre, then ring by ring, each ring starting one step south-west 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Spiral order for two rings. Ring k holds 6k cells, so a region of radius r has 3r² + 3r + 1. Radius 256 gives the default's 197,377.

Generation

One seed, up to a hundred attempts

Each attempt forks its own sub-seed and builds a complete world in its own memory arena. If the main continent lacks any of eight required terrain kinds, or too many caverns are sealed, the whole arena is freed and the next attempt starts clean. Seed 42 at the defaults is accepted on attempt 1.

The generation pipeline: seed, attempt, terrain, sublevels, caverns, springs, rivers, costs, rescue, calibrating, validating, accepted world seedone u64 attempt Nfork "attempt-N" terrainheights, biomes, sea sublevels ×3700 · 200 · −500 m cavernsmouths, trunks, branches springs500–1,500 m up rivers, lakesan integer flow network costsparallel bake · components rescueshafts · galleries calibratingmedian step cost validating8 tags · ≤ 2% sealed accepted worldthen villages, roads reject: free the arena,try the next sub-seed (≤ 100) only the surfaceis seeded with water Each stage forks its own stream from the attempt seed ("land", "forest", "sub-700-cave", "mezzo", "springs", "rivers", "water-names", "mezzo-rescue").

Where the time goes

Generation time per stage for seed 42 at the defaults, measured for this snapshot with a ReleaseFast build on darwin-arm64. The whole world took 206 ms on the command line. Costs and the three sublevels dominate. Before an index was added on 2026-08-30, the rescue stage was 98% of a size-11 generation: 134.7 of 137.1 seconds.

Timings depend on the machine and its load; the shares are what matter.

Depth

A slice through the island

The land noise is squared, which flattens the coast into lowlands and sharpens the peaks. A cavern field exists only where the noise allows and the surface above it, and above all six neighbours, clears the layer. Tunnels are dug from cave mouths toward the nearest cavern of each layer in turn; they are the only links between levels.

A vertical slice through the island: altitude bands, three cavern layers and the tunnels between them 2,000 m 1,500 1,000 500 0 −500 −1,000 high mountains above 1,500 m · no forest mountains above 1,000 m Sublevel 700: column + 6 neighbours above 700 m hills above 500 m · springs 500–1,500 m Sublevel 200 · cave mouths only above 200 m sea level: below-zero fields joined to the rim Sublevel −500: may lie under the sea floor cave mouth tunnels: the only links between levels dead-end branch, 2–6 fields rescue shaft into a sealed pocket a cavern under the sea The renderer's slab floor, −2,500 m, is below this crop;nothing in generation enforces it.
Schematic, not to horizontal scale. Altitudes are true to the generator's thresholds; tunnel steps scale with field size (at most 50 m of height per 100 m step).

Fields per level, seed 42

What the surface is made of

The upper cavern layers starve by construction: a field at 700 m needs a broad massif above it. Tags overlap, so forest fields are also lowland or hill fields.

Hydrology

Water that solves itself

Springs pour integer units of water into a network of vertices (fields sharing one water level) and segments (flows between them). Each time a vertex with surplus is taken off the worklist, one rule moves that surplus a step. Rivers are places on walkable land; only lakes change the terrain.

The flow solver: each surplus goes to the sea, the ground, a lower neighbour, or raises its basin a vertex withsurplus b a member fieldis ocean? no neighbour onits own level? a neighbourlies lower? a basin: can it affordone more metre? nonono yesyesyesyesno → the sea → the ground flow to a randomlowest neighbour rise, store,merge lakes,requeue rise⌊b/n⌋ m,rest sinks Invariant, tested: Σ springs = Σ (lakes + sea + ground). Seed 42 at the defaults: spring mass 2,945 = sink mass, across 10 rivers and 9 lakes.

Movement

What one step costs

Every directed edge between neighbouring fields is priced once, in parallel chunks of 512 fields, and the price is what both pathfinding and walking time read. A step that is too steep is impassable. Movement types never mix: a border between land and water costs nothing because it does not exist.

The cost of a land step as a chain of multipliers base1,000 × terrainhigh mtn 4 · mtn 2hills 1.5 × coverforest or fungi 1.5road instead 0.75 × steepness(1 + |dz| / (ref/2))²impassable above 3 × uphillmax(0.5, 1 + dz/ref) = costu32, never 0 ref = √(1000 · field size in metres). Water, tunnel links and cross-level links are a flat 1,000. While roads are being laid, an existing road costs a further × 0.75, so later roads reuse trunks.
Step costs at 1 km fields
One step, 1 km fieldscost
flat open ground1,000
road on the flat750
hills, or forest1,500
hills and forest2,250
mountains2,000
high mountains4,000
300 m uphill on the flat3,328
300 m downhill on the flat1,792
400 m either wayimpassable
The steepness gate by field size
Field sizesteepest stepangle
1,000 m366 m20.1°
500 m259 m27.4°
250 m183 m36.2°
100 m (default)116 m49.2°

The gate widens as fields shrink: the same slope limit allows steeper ground over a shorter step. A test pins 115 m passing and 116 m blocking at 100 m.

Worth knowing

The terrain noise draws no random numbers. Each grain is a hash of the seed and the position, so the heightfield cannot depend on draw order.

Cave mouths have a floor of six, chosen without randomness. If the per-field roll finds too few, the highest field of each of six spiral-order buckets is promoted, so worlds that already had enough stay byte-identical.

Tunnels have no neighbours. A tunnel field is a chain of links; an early coarse planner that counted only in-level edges saw the whole underground as rock.

Components are labelled at push, not pop. At map size 11 that turned 40.1 million queue pops for 10.5 million fields into one pop per field.

The main continent is the largest land component that contains surface land. Caverns and tunnels count as land, so it normally includes the underground reachable from it.

A 16-bit component id ran out. Size 11 has 136,582 components against a ceiling of 65,536; ids became 32-bit with an explicit "none" sentinel rather than an optional.

Layer 2 · Life

Bodies, needs, and food that has to exist

Every creature is a body steered by a controller. A daily clock makes them hungry and sleepy; controllers turn needs into plans; plans become timed events. Food is never conjured: it is grown, fished, hunted, scavenged or carried, and an unfunded meal stays unfunded. Before play begins, a generated past of 150 years hands over families, homes and accounts to these exact rules.

Anatomy

Every entity is a body and a controller

Two independent tagged unions. The schedule wakes a controller, never a body. A wolf, a monster and a dragon share one body type and differ only in who decides; a carcass has no controller at all, no schedule slot, and draws no random numbers.

body ↓ · controller →peoplegrazerpredatormonsterdragonshipspawnernone
herovillager, hero
groupparty
herddeer, woodlice, beetles, newts
animalwolfbrute, hound, maw wormdragon
shipship
carcasscarcass
clutchclutch of eggs
no bodyvillage, chasm, wreck

The loop

Needs → decision → one event

Needs are integer counters. Hunger rises at six signals a day; a single sleep signal is enough to want sleep; fatigue is the length of every walk. When a counter crosses its threshold the controller inserts an action at the top of its plan; an empty plan is refilled by the controller's own policy. Every step of an action emits exactly one event: an agent that emitted nothing would fall off the schedule forever.

The agent loop: a nature clock feeds needs, needs raise impulses, the controller plans, each step emits one event, and the event wakes the agent again Nature clock signals, every day Needs hunger · sleep · fatigue Impulses counter over threshold act(): the controller's turn starve? fight? then plan Plan stack or makePlans(policy) actions.step emits exactly one event The queue ordered by (tick, seq) Event executes food moves, kills, practice +5 awake, +1 asleep insert at plan top top action push pop when due walks add fatigue wake the invoker: it acts again before the next event runs
A day on the nature clock: six hunger signals, sleep signals by species, six time labels, and the rollover 00 06 12 18 people, deer pale newt maw worm wolf brute woodlouse hound beetle dragon* one day8,640,000 ticks hunger ×6 sleep, by species grow, then new day * only while a dragon is alive. Six time labels mark every fourth hour.
VILLAGER

Wary after a sighting: rest. Otherwise the first job the village store is short of; otherwise rest.

HERO

Unload at home; with fewer than 10 food units go and find food; otherwise wander the component.

GRAZER

Flee if just hunted, split at the cap, a weekly pasture check (calve or lay, or one starves), rest at night, roam by day.

WOLF

Whelp 2–4 after 30 meals if fewer than six wolves are within 6 km; rest in its sleep hours; roam. Starves after 12 days.

MONSTER

Off cavern ground, go home; rest in sleep hours; roam. Bred by chasms, at most two alive per chasm.

DRAGON

Hungry about every three days: hunt within 25 km, then anywhere; carry the catch home or kill on the spot; patrol from its peak.

Ecology

Who eats whom

Grass is kept per field and regrows daily; a herd's weekly check calves only if the pasture in range can feed every animal of its species there, other herds included. Predators eat carcasses where they lie; people take the skin first, then up to ten units of meat.

Who eats or kills whom: grass and fungi feed herds, herds feed wolves, monsters, dragons and people; farms and banks feed village stores Dragon 1,200 strength Wolves packs by standing Carcass rots in 3 days Monsters brute · hound · worm People villagers · heroes Deer herds split at 12 Crawler herds cavern grazers Clutch 3–6 eggs, 10 days Village store 20 t · pantries Grass Fungal pasture Farms Fishing banks graze graze lay hatch reap fish pantry, hand-outs 59% alone, 81% as three skin, then 10 meat snatch ≈ 97% food hunt ≈ 71% meat hunt 1 egg = 1 meal maul pelt hunt battle: duels to the last snatch ≈ 92% Coloured arrows are rolls: hunts and snatches. Grey arrows are grazing, eating and carrying; dashed, a carcass left by any kill or starvation. Wolves never attack people.

Chance

A hunt or a duel is one weighted roll

No wounds, no hit points: one draw decides. Odds below are at mean strength and rank 0. Experience shifts them slowly: ranks double in cost (1,000, 3,000, 7,000 XP …) and each adds 5%.

Every hunt and duel is one weighted roll: the attacker wins if a uniform draw lands in its share A person hunts a deer hunter 100 deer 40 70.9% Three wolves on one field hunt a deer pack of three 180 deer 40 81.4% A person duels a brute person 100 brute 450 18.1% A dragon snatches a person dragon 1,200 person 100 92.2% Roll a uniform integer in [0, attacker + defender + edge − 1]; the attacker wins below its own weight. The edge is one untrained strength point (10,000 power units), the old Python randint bug kept as a rule. A battle repeats duels between random fighters until one side is empty; a weapon adds 20%, each skill rank 5%.

Economy

Every unit is a real transfer

Three functions write items, and each is tallied per kind: grant, consume, transfer. Capacity is mass: a pack carries 260 kg scaled by strength, a store 20 tonnes. Grain's stack limit, 480 units, is exactly one six-hour reaping trip at 40 kg an hour, so a trip is never clipped.

The flow of goods from farms, banks, mines and hunts through packs and the village store to pantries, heroes and the workshop Farm, 8 ha reap 240 kg per 6 h trip Fishing bank 8 kg per 4 h trip Mine vein, 1 t 20 kg ore per 4 h trip Hunts pelt, hide, ≤ 10 meat Worker's pack 260 kg × strength Village store 20 t, mass only Household pantries topped up to 7 days, daily A hero's pack ≤ 30 per food kind Workshop, 4 h a batch ore → tool or weapon · skin → garment this trip's load only first visit: +1 weapon inputs outputs, want 20 each borrow a tool: work 25% faster No money and no market: a worker picks the first job the store is short of (food 10 t, pelts 20, ore 200, 20 of each good), and every unit is a real transfer. Every 20th tool-assisted job wears out one tool. The winner of a battle loots what it can carry; the rest is lost.
ENERGY, NOT MASS

Grain, rations and eggs carry 3,400 kcal/kg, meat 1,200, fish 1,000. An adult needs 2,040 kcal a day: 1.2 units of grain, or about four fish.

PANTRIES

At each day's rollover every household pantry is topped up toward seven days of need, settlements and homes in a fixed order. A short store serves the same homes first.

TOOLS

A borrowed tool makes work 25% faster. Every twentieth tool-assisted job wears one out, booked as a debt to the village.

The generated past

A century and a half, in a few seconds

A new world can open with a past: one to three hundred years of births, deaths, partnerships, harvests and hunger, computed year by year at the scale of households. At the opening date T the past is frozen and handed to the exact, event-driven laws of play. Durable people carry their records across.

The generated past: settlements, homes and families, then an annual loop of 13 stages, then a frozen boundary handed to detailed life Settlement requests 6 peoples × 3 villages Homes and farmland 30 home plots a village Ecology sources 1 km parcels, deer support Founding families kinship from year 1001 THE ANNUAL LOOP · 1 TO 300 YEARS, 150 BY DEFAULT · "HISTORY-COARSE-V2" begin food deaths open lists match ×13 births publish order the year sources accounts care Boundary at T a frozen packet Transition people, homes, animals staged Detailed life exact laws, one shared queue Spawner optional arrivals deer → ⌈D/6⌉ herds The same birth, death and partnership laws govern the coarse past and detailed play. Nothing crosses T half-done: no pregnancy, scarcity or store.

Seed 42's past, decade by decade

924 people alive in 1001, 694 at T in 1151; 917 partnerships, 38.5% between cousins. history-coarse-v2, default settings, measured 2026-09-29 for spec 140.

Farmland decides which villages die out

360 villages over 20 seeds and 150-year pasts (spec 140). Infant mortality lands on the tables: humans 19.8% measured against 20.0%, goblins 42.2% against 40.0%; the goblin excess is hunger.

How a world opens
How a world opensspawner onspawner off
history on (default)the past, then new arrivalsthe past only
history offfounders with no past, then arrivalsland, animals, empty chasms and ships; nobody

The population model

Who is on the record, and how they live through two clocks

Every person who ever lived in the generated past or in play is a durable record in one population store, separate from the play entities that walk the map. The store is built year by year in the past, handed over whole at the opening date T, and then advanced by exact, event-driven laws. Nothing in it is saved: a load regenerates the past from the seed and replays play.

The durable records
RecordHolds
personparents, partnerships, people and faction, sex, birth and death, heritable traits, a physiology of over 18 KB (exposure and milk histories), skills and occupation, role (villager or hero)
partnershiptwo partners, its dates, and how it ended: death, both died, separation (deferred)
deliverya birth: bearer, other parent, conception and date, the children, stillbirths
householda sorted member list and nothing else: no head, no roles, no dates
homeits settlement, condition and pantry; the pantry belongs to the home, not the household
title sharean owner's share of a home, the steward village, the beneficiary household, succession
residencewhere a person lives, and their carer while care is required (under 15 actual years)
settlementno record at all: only an id stamped on homes, titles and provenance; its faction is read from its first resident

Every id is a 64-bit number that is never reused. Kinship beyond parents and partners (siblings, cousins) is computed by walking up to eight generations of ancestry.

The two clocks
ClockHow it advances
the past16 annual stages per year: begin, food for homes and people, deaths, partnership openness, lists and matching, births, publishing partnerships, ordering and publishing the year (succession, survivors), wildlife sources, accounts, care, finish
the handover at Tthe store is handed over, not copied; a frozen packet hashes it; transition gives every living resident a body at home, binds it to its record and stages animals from the past's counts
playone queued population event at a time, at the earliest of the next meal boundary (at most a day ahead), the next biology change and the next partnership opportunity, forecast on private workspaces

Births, deaths and partnerships follow one set of laws at both speeds: 13 mortality bands scaled by nutrition, care and housing; conception chances by age; partners weighed by contact and age gap, with cousins only under scarcity.

Named streams, never shared ones. The past draws from history-coarse-v2/{year}/{person}/{purpose}; play's episodes from population-v1/person/{id}/{purpose}/{seq}, numbered by a store-wide counter, so one extra draw would shift every later episode.

A state digest names the whole store. Each newer table is digested only when it is non-empty, so a world without it keeps the digest it had. Six frozen test values pin it.

Partners mostly live apart in the past. Publishing a partnership moves no one: the generated past never changes a residence, so a household is a founding family and its descendants. Spec 156 brings households on the road.

The store is the largest thing in a world. About 6,600 person rows after 150 years, mostly the dead, at roughly 18 KB each; the history job runs under a 1 GiB budget.

This snapshot's week

Seven days of seed 42

Measured for this page with mal-headless run --seed 42 --days 7 --stats: the run ends on 1151-01-08 00:00:00, one week after the default world opens, with 18 settlements and 540 homes. Of 1,944,263 events, 1,736,368 are single footsteps; the rest are below.

812people on the record
953dead, all told
2,430deer in 652 herds
45wolves
451sightings, 386 flights
2,152figures in the chronicle

Events by kind, footsteps aside

Worth knowing

A pack is just wolves standing together. A wolf hunt weighs every living wolf on the field; there is no pack membership.

The carcass exists before the kill. A hunt creates it first, so a herd emptied by its last deer is still credited to the hunter.

Dragons are on no field while flying. Nothing on the ground can fight one in the air; only take-off and landing are exposed.

Villagers flee what they see. A monster within 300 m (a dragon within 1 km) sends every other villager about 600 m directly away, wary for three hours. Heroes never flee.

Two laws for deer. The past counts deer per km² against woodland support; play feeds herds on per-field grass. At T each source's deer become ⌈D/6⌉ herds.

Monsters are counted by a full roster scan at every chasm spawn, on purpose: a counter kept right through every death would be harder to trust.

Layer 3 · Caverns

One queue, first in, first out

Malsimulation is a discrete-event engine, not a frame-stepped one. Time is a 64-bit integer. Everything that happens, from a footstep to a hunger signal, is an event in one priority queue ordered by tick and then by insertion number. Nothing is snapshotted: a save is a recipe, and loading cooks it again.

Time

A tick is a hundredth of a second

A year is thirteen months of 28 days. The default world's generated past starts in the year 1001 and runs 150 years, so play opens on 1151-01-01, at tick 3,616,704,000,000.

Units of simulated time as integer ticks, on a logarithmic scale tick 1 ticks 0.01 s second 100 ticks minute 6,000 ticks hour 360,000 ticks day 8,640,000 ticks 24 h month 241,920,000 ticks 28 days year 3,144,960,000 ticks 13 months · 364 days Bar length is logarithmic. Ticks are u64, enough for 5.9 billion simulated years; the only float is the sun angle for the renderer.

The engine

What one advance does

Advancing pushes an "end of advance" sentinel and runs events until it pops. Each event is executed, traced, and its slot returned to a pool; any agent it woke then decides and schedules exactly one new event before the next event runs. Event slots carry a generation number, so a stale reference to a reused slot reads as nothing.

One advance: push a sentinel, pop events in tick and sequence order, execute, trace, let woken agents act, until the sentinel pops advance(amount) push the sentinel at now + amount deadline passed? checked after ≥ 1 event pop the smallest (tick, seq): FIFO on ties still active? cancel is soft: skip it execute 35 kinds of event trace + release one JSONL line, slot reused drain the woken agents each acts: exactly one new event was it the sentinel? window closed return: done no yes yes no: next cancelled: skip yes: return,window stays open An agent that an event wakes decides before the next event runs, and pushes its one event with the next seq number.
The sentinel: events at its tick run inside the window only if they were queued before it now seq 41walk hop seq 42eat seq 44hunger signal ONE TICK: NOW + AMOUNT seq 45 · queued before the callruns inside this window seq 46 · the sentinelthe window closes here seq 48 · created during the windowwaits for the next one This is why "one hour" equals "two half-hours": cutting a window in two cannot reorder a single event (spec 030, rule L2).

Playing it

Each frame gets four milliseconds of world

The window keeps drawing while time runs because simulation is sliced: each frame advances until 4 ms have passed since the frame began, stopping only between events. The rest of the requested interval carries over, and the history is the same as one uninterrupted advance.

One frame: input, up to 4 ms of simulation, camera, HUD, snapshot through the facade, render input simulate ≤ 4 ms camera HUD snapshot render + present advanceSlice(amount, deadline): stops only between events a window still open carries over to the next frame The snapshot asks the facade for plain views (agents, places, water, roads, the sun angle) into a per-frame arena; walkers glide on an eased completion rate. A single long event can still overrun a frame: a separate play thread is FND-10.
SPEEDS

Eight rungs from 1× (100 ticks a second) to 10m (a billion: about 116 days a second). The default is 10×.

INTERVALS

Advance a minute, ten minutes, an hour, six hours or a day: each is one window, finished across as many frames as it needs.

AUTOPLAY

A fixed 1/60 s step with at most four catch-up steps; a backlog beyond that is dropped rather than chased.

Pathfinding without stalls

Walks wait for a batch

An agent that decides to walk does not search on the spot. It files its request and waits twenty simulated minutes; the first waiter to wake solves every pending request at once on the thread pool. An answer is a pure function of terrain that no longer changes, so the history is identical at every thread count. This snapshot's week: 57,192 searches in 477 batches, 119 requests a batch on average and 659 at most.

A route batch: walkers file requests and wait twenty minutes; the first to wake solves them all in parallel walker A walker B walker C solveAll file (who, from, to), then wait 20 minutes A wakes first and answers every pending request one scratch per worker; answers copied back in filing order

The only door

The facade

The renderer, the interface and the headless tool see the simulation through one file. A handful of functions change the world; everything else is a view, written into the caller's memory as plain data.

The facade: the platform and the headless tool talk to the simulation through one file, commands in and plain views out app · ui · render the platform side mal-headless gen · run · save · load FACADE.ZIG 98 public functions + 6 re-exports commands in: newWorld · deinit restartAgents advance · advanceSlice abandonAdvance intervene the simulation, private schedule · events · actions agents · controllers · nature battles · hunts · production routes · items · chronicle population/* (33 files) the RNG, the queue, the arenas commands plain-data views Views are written into the caller's arena: AgentView, PlaceView, WaterBody, PolyLine, census, cards, Legends. They carry values, never pointers into the queue. A shell guard fails the build if render, ui or app import eight named simulation internals.

Most of the door is windows

Seven functions change the world: newWorld, deinit, restartAgents, advance, advanceSlice, abandonAdvance and intervene, plus the jobs that build a population while a world is being made. The other ninety-odd only look.

Counted by purpose for this snapshot, by reading the file.

The 98 functions, by purpose

Vocabulary

Thirty-five kinds of event

Every one runs through the same queue. Nature's six kinds have no invoker: a signal walks the whole roster in insertion order. A default day schedules 22 of them, 23 while a dragon is alive.

agent activity 11

wait · go_to · eat · sleep · rest · refill · work · hunt · maul · scavenge · battle

animal life 8

graze · calve · lay · hatch · split · starve · whelp · rot

spawners and ships 6

spawn_hero · regenerate_spawn · shipwreck_spawn · ship_arrival · disembark · ship_departure

dragon flight 4

take_off · descend · land · eat_catch

nature and system 6

signal · time_label · new_day · grow · population · end_of_advance

Memory of the world

The chronicle remembers; it never decides

History is recorded as it happens: figures, moments, the mentions that tie moments to figures, and every step walked. In this snapshot's week: 2,152 figures, 5,644 moments and 7,380 mentions. Legends reads it through seven lenses: heroes, bands, villages, ships, relics, beasts and days.

The chronicle keeps four append-only shelves of fixed 1,024-element chunks figuresa person, beast, band, village, ship, relic table 1,024 1,024 1,024 1,024 1,024 moments22 kinds: born, died, battle, landed … table 1,024 1,024 1,024 1,024 1,024 mentionsthreads a moment onto each figure's story table 1,024 1,024 1,024 1,024 1,024 stepsone per field walked: half the memory table 1,024 1,024 1,024 1,024 1,024 1,024 1,024 Chunks never move and growth never copies. No RNG, no events, and no decision reads it. It is not saved: a load rebuilds it through the same writers.

Persistence

A save is a recipe

Ten fields: the format, the build, the seed, every simulation setting, the elapsed ticks, the player's journaled acts, the opening tick, the detailed time, a digest of the population and the history length. A year of seed 42 once saved as 95 lines, 4.0 KB.

Loading a save: parse, regenerate from the seed, compare, replay the player's journaled acts, advance to the saved time a save file ZON text, format 3 parse and refuse other build? bad times? regenerate seed + the file's own settings compare the regenerated past vs the file replay the journal advance to tick, intervene advance to the end elapsed ticks, then --days chronicle rebuilt by the same writers as a side effect A save stores the recipe, not the world. Loading on another build is refused: a seed names a world only within a release (ADR-011).
// world-42-t3616764480000.zon, abridged and illustrative
.{
  .format = 3,
  .build_version = "0.3.0-dev",
  .seed = 42,
  .sim = .{ … every setting … },
  .elapsed_ticks = 3616764480000,
  .interventions = .{
    .{ .tick = …, .act = .{ .smite_person = … } },
  },
  .startup_tick = 3616704000000,
  .detailed_elapsed_ticks = 60480000,
  .population_digest = 32 bytes,
  .history_years = 150,
}

Why replay reproduces

The same build, seed and settings regenerate the same world and the same random streams. Cutting time into windows is history-neutral. An intervention goes through the same function live and in replay, and the chronicle is rebuilt by the same writers.

The save holds its own copy of every setting, so a local settings.zon cannot change what a load produces; and the plan is checked against the world actually regenerated, not against the file's claims.

What comes next

Six ways of deciding, and the one that will replace them

Each system grew its own way of choosing. AGT-12 builds one decision core (minds of twelve motives, collectives with roles and procedures, an obligations ledger, scored choices with commitment) and AGT-14 moves these loops onto it one at a time. Designed in specs 164–166; not built yet in this October 3 snapshot.

October 7 amendment: Delivery A (spec 164) is now implemented: read-only minds, collectives, duties and seeded relationships. The scored decision core and its first adopters in specs 165–166 remain unbuilt.

Today's decision loops and their future
TodayWhereHow it decidesBecomes
impulses and a plan stackheroes, bands, animalscounters cross thresholds; a fixed policy fills an empty planheroes and bands first, in spec 166: scored offers, bands as collectives led by decree
a priority listvillager workthe first job the village store is short ofthe village's agenda; work requests as obligations each villager weighs (AGT-14, first)
annual lawspartnership, spec 154's departuresa chance per period; weighted candidate drawsdecisions at life events and reviews, at both speeds (AGT-14)
consent ruleshome titles, spec 156's movesowners and the village agree by rulecollective procedures (AGT-14, with households as collectives)
support commitmentshousehold care and provisioninghousehold plans and offersobligations in the ledger (AGT-14)
fixed wants and hostilityvillage stores, factionsconstants; "different faction means fight"interests on an agenda; stances between collectives (AGT-4)

Worth knowing

The trace hash hashes event names. Each line is tick, kind name and actor serial, so renaming an event kind moves the golden with no change in behaviour.

An actor is a serial, not a slot. Entity slots are pooled and reused; a never-reused serial stamped at birth is what the trace and the chronicle record.

Thread count is not part of a world. It is deliberately outside the saved settings: it changes wall time and nothing else.

Interventions are not events. A smite or a razing applies between events through one function, live and in replay, and is journaled at the tick it happened.

An idle spawner keeps itself alive with a one-day wait, because an agent with nothing scheduled would never be woken again.

The calendar exists twice: once in content data that rolls the months, once as constants that print dates. A content test pins them to 28 days and 13 months.

Layer 4 · Tunnels

Seven modules, one wall

The simulation is pure logic that never sees a window: the headless binary links no SDL at all, which proves it continuously. The renderer, the interface and the application sit on the other side of a wall and reach the simulation only through its facade. Memory is owned by lifetimes, not by objects; concurrency is bounded and deterministic by construction.

The graph

Who may import whom

core ← worldgen ← sim never import SDL or ImGui. ImGui appears only in src/ui. Two binaries come out: mal, the only one that links SDL, and mal-headless, which carries the determinism anchors. A third, population-check, is a run step for validating the population model.

Module graph: core, worldgen, sim and cli never see a platform; render, ui and app reach the simulation through sim.facade PURE LOGIC · NO SDL, NO IMGUI THE PLATFORM SIDE core lattice, ticks, RNG, world, A*, jobs worldgen fractal, terrain, mezzo, rivers, costs sim schedule, agents, population … cli → mal-headless, no SDL sim.facade render SDL_GPU, meshes, camera ui the only Dear ImGui app → mal: the loop, the keymap SDL3 3.4.16 ImGui 1.92.1 views commands Arrows point from importer to imported. Three greps in ci/check_boundaries.sh enforce the dashed wall, the ImGui fence, and the facade.

The code

Where the 197,056 lines live

Every rectangle is a file, sized by its lines and grouped by module. The population model alone is 88,022 lines, much of it contract tests and fixtures; the facade is one 10,000-line file. Select a file to open it at the snapshot's commit.

Tests, by module

1,931 test declarations. zig build test runs them as 30 cached processes: 18 unit shards and 12 end-to-end shards, dealt round-robin. Zig hands every test run a fresh random seed that would bust the cache, so the build pins it to zero; nothing in the repository reads it.

zig build test-unit skips the end-to-end tests, whose names begin e2e: : the edit loop.

Memory

An arena per lifetime

No object is freed alone. The world arena holds what generation built; the simulation arena holds entities, the schedule and plans; a scratch arena is reset before every search; a frame arena is reset every frame. GPU buffers are allocated once, rewritten in place, and count their own reallocations, so "allocated once" is measured rather than hoped. This week: a 187,743 KB simulation arena beside a 79,732 KB world arena.

Memory arenas by lifetime across Generate, play, Restart and Generate again Generate play Restart play Generate world arenafields, places, links sim arenaentities, schedule, plans attempt arenasa rejected world is freed whole scene arenasCPU meshes until GPU upload scratch arenareset before every query frame arenareset every frame GPU buffersallocated once, regrow ×2, counted Restart now regenerates the whole world privately and swaps it in (2026-09-21)

Concurrency

Threads that cannot change history

One worker generates a world while the loading screen draws. A job pool fans out pure work: the cost bake, mesh building, route batches and flora scatter. Its results are bit-identical at any thread count, so the pool changes wall time and nothing else (ADR-012).

Threads: the main frame loop, one generation worker, and pool workers spawned per call main thread generation worker pool workers loading screen keeps drawing each frame: ≤ 4 ms of simulation, then draw newWorld buildScene atomics: done, failed cost bake scene tasks route batch route batch flora Workers are spawned per call and joined before it returns; chunk boundaries depend only on problem size, and results merge in chunk order. Every agent decision and every pop of the queue stays on one thread. A route batch runs between two events, never across one.

Decisions

Twelve architecture decisions

The ADR log is append-only: a decision is amended by a later one, never rewritten.

ADR-001

Zig + SDL3 + SDL_GPU

Zig 0.16 pinned; Metal, Vulkan and D3D12 through one API, with no other runtime dependency.

ADR-002

Structural parity, not bit-exact

The rewrite kept the character of the Python worlds, not their bytes.

ADR-003

Integer ticks, a vendored PRNG

So a standard-library upgrade cannot change a world.

ADR-004

A snapshot facade

Typed views out, typed commands in, enforced by a guard.

ADR-005

Precompiled shaders, committed

GLSL once; SPIR-V, MSL, DXIL and DXBC generated and checked in.

ADR-006

No portable line width

Every line and marker is an instanced quad sized in pixels.

ADR-007

Arena per lifetime

World, simulation and frame arenas; GPU dynamic data allocated once.

ADR-008

Vendor Dear ImGui

Built against our SDL, so one binary never holds two.

ADR-009

Nothing resolves against the working directory

Assets beside the executable; settings and logs in the app-data folder.

ADR-010

Generated over maintained documentation

The controls page and the version mirror are generated and test-checked.

ADR-011

Goldens are regression tests, not a veto

A moved golden is a question; a seed names a world only within a release.

ADR-012

Shared-memory threads in one process

Determinism lives in the primitives; a process split stays possible.

Layer 5 · Bedrock

Determinism, down to the bit

Within one release, the same seed, settings and interventions produce the same history, on every machine and at every thread count. That promise rests on five mechanisms and three frozen hashes, and it is what makes everything above it, from replay to the generated past, possible to trust.

Five mechanisms

01 · INTEGER TIME

Ticks are u64 hundredths of a second. No float ever decides when something happens.

02 · A VENDORED PRNG

xoshiro256++, seeded by SplitMix64, forked into named streams. A compiler upgrade cannot change a world.

03 · ORDERED ITERATION

Fields, random draws and vertices all follow the spiral. Nothing iterates a hash map where order matters.

04 · FIFO TIES

The queue orders by (tick, seq). Simultaneous events run in the order they were scheduled.

05 · DETERMINISTIC ∥

Chunks are cut by size alone, writes are disjoint, merges run in chunk order, and the lowest-numbered error wins.

Where the three goldens sit: the world hash after generation, the trace hash after a day, the RNG golden under everything seed 42 fork "attempt-N" worldgen stages spiral order, ∥ bake WORLD HASH 0x584d5fc099546a3c fork "sim" opening + 1 day (tick, seq), batches TRACE HASH 0x3ba7802c37fed0bc RNG GOLDEN · Rng.init(0) → 0x53175d61490b23df … seed 42, size 4,1 km fields, 1 cavern a 1-year past, then1 simulated day Each frozen in a test. A golden that moves fails the build; the change must explain itself in the same commit, with old and new values (ADR-011).
Checked for this snapshot. The week this page measured, seed 42 at the defaults, ended with trace hash 0xea0494938d7252d5: identical to the end-to-end anchor frozen in the tests (0xea0494938d7252d5). The trace golden's own test lists 28 earlier values, each a deliberate move explained in its commit.

Randomness

Streams are named, not drawn

Every consumer of randomness forks its own stream from a label. Adding a stream, or drawing more from one, never shifts the numbers another stream sees. The noise that shapes the terrain draws nothing at all: it is a hash of the seed and the position.

The random streams form a tree of labels forked from the world seed world seed "attempt-N" ≤ 100 tries "sim" the simulation stream "land" · "forest" "sub-700-cave" · alt · fungi "sub-200-…" · "sub--500-…" "mezzo" · "mezzo-rescue" "springs" · "rivers" "water-names" per-request forks a settlement anchor, a name … forkSeed(seed, label) = seed XOR wyhash("mal-fork", label): a stream is named, not drawn, so adding one never shifts another.

The generator itself

xoshiro256++ keeps 256 bits of state and is vendored rather than taken from the standard library, so a Zig upgrade cannot change a world (ADR-003). The world and trace hashes use the standard library's Wyhash: a change there would move those goldens but not the RNG golden.

The simulation's own stream is forked from the seed with the label "sim". There are 94 fork sites outside the generator itself.

// xoshiro256++, one step
result = rotl(s0 + s3, 23) + s0
t  = s1 << 17
s2 ^= s0;  s3 ^= s1
s1 ^= s2;  s0 ^= s3
s2 ^= t;   s3 = rotl(s3, 45)

// seeding: four SplitMix64 outputs
0x9E3779B97F4A7C15 · 0xBF58476D1CE4E5B9
0x94D049BB133111EB

// integers: unbiased by rejection
// floats: the top 53 bits
// normals: polar Box–Muller,
// no cached spare, so draws pair up

Pathfinding

A* that prefers to be a little wrong

The open list orders by (f ascending, g descending, field id): deeper nodes first, and fully deterministic. The heuristic is the median land step cost times a weight of 3.0 times hex distance. That is deliberately inadmissible: routes come out a little longer and searches far cheaper, because people are not perfect path finders. A search capped at a million nodes returns a partial path to its most promising node.

Heuristic weight against search effort
Heuristic weightnodes per searchroutes longer by
1.0, admissible33,4852.31%
3.0, shipped15,62517.34%

From the measurement that chose the weight (spec 106). A coarse-corridor planner is fully built and switched off: it closed 18% fewer nodes and saved no wall-clock time, because A* here is memory-bound.

57,192route searches this week
20,348,235nodes closed
355nodes on average
189,418in the worst search

Pixels

From views to a frame

SDL_GPU drives Metal, Vulkan and D3D12 through one API. Static geometry is built on the generation worker, twenty mesh tasks run on the pool and are assembled in list order, so the scene is byte-identical at any thread count. Each frame then uploads only what moved.

A frame on the GPU: facade views, dynamic-buffer uploads, one world pass per visible level, overlays, then the ImGui pass facade viewsagents, places, sun uploadsdynamic buffers, copy pass world passcolour + reverse-Z depth overlay passImGui HUD submitpresent INSIDE THE WORLD PASS, IN THIS ORDER terrain + skirt tubes water rivers, roads flora canopy buildings + figures markers, trail, sun highlight agent dots dashed: once per visible level (indexed by level id) · solid: once, over all levels Depth is reverse-Z (clear 0, compare greater). Lines and markers are 6-vertex instanced quads: Metal draws only 1-pixel lines and D3D12 has no point size. Markers are pulled toward the eye in the vertex shader rather than lifted in metres, so they sit on the ground at every distance.
The shader pipeline: GLSL compiled to SPIR-V, MSL, DXIL and DXBC, one per graphics backend GLSL 18 stages, 9 programs SPIR-V glslang -V MSL 2.1 spirv-cross --msl HLSL, SM 6.0 spirv-cross --hlsl HLSL, SM 5.1 spirv-cross --hlsl DXIL dxc 1.8, signed DXBC fxc Vulkan Linux, Steam Deck Metal macOS, entry main0 D3D12 DXIL, or DXBC below SM 6 Windows CI Windows CI All 108 blobs (18 stages × 6 kinds) are committed and embedded in the binary. The device claims exactly the formats it carries. A DXIL blob whose container hash sums to zero is unsigned; the build refuses it because D3D12 would.

Proof

The harness

One test binary per module, each split into cached shards; the end-to-end tests run whole histories. CI builds and tests Linux and Windows only when a commit is pushed to a release branch, and does not run the renderer: four real bugs in this project's history were invisible to CI and obvious within a minute of running the binary elsewhere. Rendering changes are checked against committed offscreen captures.

Thirty test processes: unit and end-to-end shards per module sim cli render app core worldgen ui unit shard (18) end-to-end shard (12)

Every hash seed spells its name: 0x6D616C2D666F726B is "mal-fork", 0x…776F726C "mal-worl", 0x…74726163 "mal-trac".

The vendored generator is checked against the one it replaced: its first 16 outputs must equal the standard library's xoshiro before the frozen literals are compared.

Terrain normals are half-parallel on purpose: faces in parallel, sums in triangle order, because float addition is not associative and the mesh must be the same bytes every time.

The default window is 1024 × 768 because the Python original's 1024 × 786 was a typo that was not ported.

Drift

Where the documents and the code disagree

Found while preparing this snapshot by reading the code against the docs. They are notes, not verdicts: none was run, and each belongs to its owning spec or document to settle.

  1. Restart rebuilds the whole world now. Since 2026-09-21 it regenerates privately and swaps in; the architecture doc, ADR-007 and comments still describe dropping only the simulation arena behind a place watermark.
  2. The trace golden covers one day, not a week. The determinism doc says a full simulated week; the frozen anchor is seed 42, a small fixture, one day. A week-long anchor exists only as an end-to-end test.
  3. The facade is 98 functions, not the "complete surface" of about 26 listed in the simulation doc.
  4. The frame loop does use the pool, for flora scatter, though the architecture doc says it never touches it.
  5. The facade guard is a denylist. It refuses eight named internals; the app also reads simulation types, the chronicle and some Sim fields directly.
  6. The chronicle is written from ten modules, not the "six choke points" its header and the doc describe; the doc lists 8 moment kinds of today's 22.
  7. Opening wildlife comes from the past's counts. The doc presents the herd and litter seeders; at shipped startup deer and wolves come from the generated ecology instead.
  8. Empty work still teaches. The handbook says empty attempts earn nothing; empty fishing, sowing and reaping trips do earn practice.
  9. The worldgen doc's stage table omits rescue, calibrating and validating, and lists roads and the report, which run outside the pipeline.
  10. Three settings are read by nothing: the island-mode flag and the cavern-spring settings.
  11. Worth a look, from reading only: a durable person may schedule an inert 20-minute meal after each hunger signal; autoplay "1×" may run at 60 ticks a second rather than 100; the headless tool ignores arguments past the sixteenth.