Settlement Simulation
Inhabited settlements on the server: the three simulation tiers, the deviation-based ledger behind stock, prices and treasuries, commodities and trades, player destruction, and the stability invariants that keep it from drifting.
Partly implemented. zone-server runs townsfolk with occupations, shifts and homes, the settlement ledger (stock, price and treasury) and NPC shops. Treasuries draw their income from the world reserve, see Money Supply. Other parts of this page are still design.
Settlements are generated in full — streets, districts, buildings with door bearings, a roster of
thirty-three trades per town derived from population and terrain. The generator also produces a
household graph and a population summary designed to be re-inflated into agents at runtime. The zone
server now does that: Households.one turns a household back into its members for townsfolk, their
conversation and what they know.
This page describes filling them in: people with occupations and daily schedules, and behind those people an economy in which goods are genuinely produced, moved, sold and consumed.
The whole effort is measured against one sentence:
A player walks into a village, buys bread, burns the field outside it, comes back a Bestia day later, and the bread is more expensive.
That is deliberate. This codebase has a habit of shipping subsystems that are complete, tested and never reached. The settlement lore service and the household expander were such cases until townsfolk conversation started using them. Anything that does not move that sentence closer to demonstrable is deferred.
Three tiers, not two
The obvious split is “agents when a player is near, an aggregate ledger when not”. That misses the
tier this codebase already leans on everywhere: derived, stateless f(seed, t). Weather has no
stored state at all. Scorch regrowth “costs no writes” because the visible mask is recomputed on
read from accumulated rainfall.
So the economy stores only the deviation from a derived reference path, and that deviation mean-reverts to zero.
| Tier | Holds | Cost |
|---|---|---|
| Derived | Reference stock and price paths, roster, population, catchments | Nothing — recomputed from the world |
| Ledger | Δ stock, δ log-price, treasury, last-stepped day | One row per settlement a player touched |
| Agents | Visible townsfolk with a full GOAP brain | Capped per player, see LOD |
This is the decision the rest hangs off. An untouched settlement has no database row at all, its step is exactly a no-op, and “tick the whole world” versus “persist only what players touched” stops being a trade-off.
The settlement ledger
State
Per settlement: Δ stock deviation per commodity, δ log-price deviation per commodity, a treasury
M, and the game day it was last stepped. Keyed on the dense settlement index, with the world’s
shape and pipeline versions carried alongside so a regenerated world discards stale books — the
pattern the prop-divergence and scorch registries already implement.
Rows are created lazily on the first non-zero deviation and deleted again once everything decays back inside a tolerance.
The step
visibleStock = clamp(S_ref · season(t) + Δ, 0, warehouseCap)
price = p_ref · siteMul · seasonPrice(t) · exp(δ)
cap = capRef · health(s,t) · hunger(s)
run(t) = cap · util · min over inputs of (stock / need)
eat = P · perCapita · (p_ref / price)^ε
Δ' = Δ · exp(−(spoil + κ) · d) + flow · d
δ' = δ + (clamp(γ · ln(coverTarget / cover), −ln 2, +ln 4) − δ) · (1 − exp(−d/τ))
run is a Leontief production function: a trade runs at the smallest ratio its inputs allow. That
one line is where burn the field → no grain → no flour → no bread falls out, with no special case
anywhere.
Three numbers carry the design:
Restocking effort. A settlement in equilibrium produces exactly what it eats, so full output
alone would leave an emptied store empty. When a store is below its seasonal reference, the town
works harder: up to 60% more output, fully committed once the store is down by a third. The extra
effort is scaled by run, so burnt fields or a mill without grain cannot make up the shortfall.
Without it, every negative shock is permanent, because imports cost money and a robbed town may
have none. A store holding n days of cover refills from empty in about n / 0.6 days.
κ is inter-settlement trade, expressed as a decay rate rather than as caravans. It is scaled by
the road traffic the generator already records on each settlement, so a crossroads town refills a
shortage in about two and a half game-days and an isolated hamlet takes ten. Imports are charged to
the treasury, so a bankrupt town degrades instead of being invisibly rescued. No bilateral matching,
no O(n²) pass, and a clean upgrade path: make κ pull toward a road-weighted regional mean instead
of toward zero, of which the first version is the special case.
Production rates are derived, not tuned. For a chain ending in a household staple:
rate(baker) = perCapita(bread) · residentsEach(baker) / employeesPerBusiness
· (1 + spoil(bread) · coverTarget) / util
which comes out at about seventy loaves per baker per game-day. It follows from the trade catalogue’s own service ratio, so the generator and the runtime cannot drift apart.
Why it does not drift
At Δ = 0 the net flow is zero by construction, because the reference production and reference
demand are the settlement’s own steady flows. At δ = 0 stock cover equals its target, so the
price target is ln(1). Both are exact fixed points, to floating point.
Seasonality does not break that, and this is the point of expressing everything as a deviation: the seasonal multiplier moves the visible stock and price through the year while Δ and δ stay at zero. A town’s grain swings with the harvest and its database row still does not exist.
Three independent reasons it cannot run away, any one of which suffices:
- δ is confined by construction. It relaxes convexly toward a target that is explicitly clamped, so the clamp interval is an invariant set whatever the stock model does.
- Δ is contracting. More stock means more consumption and more spoilage and never more production of the same good, so the derivative of the update with respect to Δ is below one.
- No positive feedback loop can exist, because production of a good depends only on its inputs. That requires the commodity graph to be acyclic, which is checked at boot — with a cycle, zero becomes an absorbing state and the town dies permanently.
Commodities and trades
A commodity is a real item from the item catalogue. economy.yml binds each trade to inputs and
outputs per game-day, a reference price, spoilage, seasonality, and the building function it works
from. Three first-class kinds:
trades:produce something.retail:hold stock and sell it without producing — the general store, the market trader.unbound:produce nothing tradeable at all — temple, healer, banker. A real case, not a fudge; inventing an abstract “service” commodity for them costs a week and buys an item nobody can hold.
Every trade in the catalogue must appear under one of the three with a reason, or the server does not boot. A trade with no entry is a shop in every town in the world with nobody in it, and that should be found by a build rather than by a player.
Relationship to player recipes
Where a player recipe exists for the same transformation, the economy entry names it and the boot runner asserts the inputs and output match. It does not reuse the recipe type, for three reasons:
- A recipe requires a skill, and there is no BAKING skill. Inventing one would pollute the master skill tree and the client’s attack database, which are a three-way sync obligation.
- A farmer growing grain has no material inputs. Its binding constraint is land and season, which a recipe has no field for.
- A recipe’s success chance and cast time are per-attempt player mechanics. Folding them into NPC throughput would mean a balance change to the player’s forge silently changing the town’s iron output.
A checked correspondence, not a shared type. What matters is that a player crafting an ingot and a
town smelting one use the same materials in the same proportion. The check itself is not built yet:
today the per-units in economy.yml follow the recipes by hand (the carpenter’s half a log per plank is
the PLANK recipe’s one log for two planks).
What is bound
Of the thirty-three trades: six produce, two are retail, nine are pure services, and sixteen are blocked on a good that is not priced yet.
Two chains are bound. Farm → mill → bakery → household came first, because it exercises every mechanism at once: multiple stages, capacity damage at the farm end, a consumption sink at the household end, and spoilage on the perishable.
Timber is the second. The woodcutter fells logs; the carpenter saws them into planks and the charcoal burner chars them; the blacksmith forges nails from imported iron and burns charcoal in the forge. Residents use a few planks and nails for upkeep and charcoal as fuel. No settlement smelts iron, so ingots arrive from the outside world, like the repair kits. Felled woods reach the woodcutter the way burnt fields reach the farm.
Where a player recipe makes a commodity from other commodities, the inputs are priced at about 1.8 times the output: a log costs about as much as two PLANK recipes make of it. Crafting a priced good is then a way to make material, not money (I21).
In value order after that: raw_fish, wool/cloth, hide/leather, ale, cut_stone.
Currency
A gold_coin item, stackable, weightless. Weightless because the design forbids smaller
denominations and a fresh master’s entire carrying capacity is about twenty-five kilos — at any
non-zero coin weight, ordinary shopping becomes a logistics puzzle. The postal
system already prices gold as a
percentage fee rather than as freight, which is the reading consistent with the rest of the design.
Minting stays out of scope here. Coin enters the world only through settlement treasuries seeded from the NPC pool, so the conservation invariant is trivially satisfied until the faucet exists.
Player destruction
Three radii answer three different questions, and conflating them is the bug waiting to happen:
| Radius | Scale | Question |
|---|---|---|
| Settlement footprint | 1310 / 610 / 280 / 130 m | Was the mill burnt down? |
| Economic catchment | 20 / 12 / 7 / 4 km | Was the field burnt? |
| Resource range | 14 km | Was the deposit mined out? |
Count the damage, not the world
Counting resident entities is not merely inaccurate, it is catastrophic: static props exist only while a client holds the terrain column they stand on, so on an empty server every settlement would read zero production. Enumerating generated props is impossible in a different way — a 128 km world holds on the order of a million tree props, and materialising a 14 km catchment means hundreds of thousands of column evaluations.
So invert it: iterate the damage, which is tiny, and test each damaged thing against the settlements.
- Burnt ground. The scorch registry’s scarred columns are “a handful in ordinary play, zero most of the time”, and each scar’s visible mask already has regrowth applied. Arable area is derivable from the food capacity and cereal share the generator wrote onto the settlement.
- Felled woods. The finding that makes this affordable: a prop’s durable identity already encodes its position. The identity packs a lattice cell, and the cell size is known per kind, so the divergence table is a sparse, positioned damage set with no schema change at all. A young tree counts as the share of a grown one it still lacks. The woods a town works are the trees it fells in one regrowth cycle, capped by the trees the generator counted in its catchment — the same reading as the farmland, where a town works as much of its land as it eats. Collected props such as herbs have no channel, because no trade takes one as an input.
- Destroyed workplaces. Same decode, tested against the footprint, matched to trades by building function. Deliberately coarse — losing one of five craft buildings takes a fifth off every craft trade, because working out which one was the mill would mean a second copy of the generator’s business placement in another module.
Catchments overlap, and the generator shares contested land out by a distance-falloff weight. That weight must be reproduced, or burning a contested field hurts one village for free and the two settlements’ books stop adding up.
Two traps
A regrown prop lingers in the divergence map until somebody walks past its column, because eviction only runs on materialised columns. The damage sweep must therefore apply the regrowth deadline itself, read-only — and must not evict, which would make the economy a third writer of a map whose contract names exactly two.
Ore deposits cannot be exhausted and this will not be half-built. Ore is voxels: no prop and no
durable identity. Carved voxels are saved (chunk_edit), but nothing knows a deposit as a whole. The
later mechanism is a mine-head prop at the deposit, which slots into the felled-prop channel unchanged.
Stability invariants
Each is a boot check, a constructor requirement, or a test — never a comment. They are numbered so the tests can cite them.
Price
| # | Invariant |
|---|---|
| I1 | 0.5 · p_ref ≤ price ≤ 4 · p_ref, by clamping δ every step rather than by hoping |
| I2 | Price moves continuously; no step changes a player can be surprised by |
| I10 | bid ≤ ask · (1 − 2·spread) — round-tripping in one settlement is strictly loss-making |
| I11 | The same holds for n units at once, once price impact is included |
Stock
| # | Invariant |
|---|---|
| I3 | Visible stock is never negative |
| I4 | Stock is capped by warehouse capacity; the excess spoils at the ceiling |
| I5 | Every commodity has spoil + κ > 0, or boot fails — otherwise it is an unbounded accumulator |
| I12 | Locals eat first: only stock − population · perCapita · reserveDays is offerable |
Money
| # | Invariant |
|---|---|
| I6 | Every unit a player buys leaves the ledger; every unit sold enters it |
| I7 | Coins paid out equal coins removed from the treasury, exactly |
| I8 | The treasury never goes negative — a shop that cannot pay refuses |
| I9 | The treasury is not capped — what it holds above its target drains to the world reserve in about ten game-days |
NPC-to-NPC trade is internal to the ledger and moves no money: simulating per-NPC purses buys nothing and costs exactly the state this design refuses to keep. But a treasury that only moves on player trades is a one-way ratchet, because players are net sellers early and net buyers late. So the treasury mean-reverts to what a settlement of that size and wealth ought to hold, over about sixty game-days. The target shrinks with what the town still produces, so a town that lost its workshops is poor as well as idle. A surplus goes the other way much faster, over about ten game-days, so coin players paid into one town soon reaches the reserve and the other towns. A shop never refuses to sell because its town is rich; only the goods on offer limit a purchase.
That is not a second faucet. A player who dumps ten thousand apples drives the treasury below its reference, it refills slowly, and their second load sells into a thinner purse. The fiction is taxes and trade with the un-simulated world beyond the map — which is what a 128 km world is embedded in. The coin for that refill comes out of the world reserve, and a town cannot gain more than the reserve holds. See Money Supply.
Structure and time
| # | Invariant |
|---|---|
| I13 | The commodity input→output graph is acyclic. A cycle makes zero an absorbing state |
| I21 | Every buy-craft-sell loop is loss-making inside one town — reference prices, the shop’s spread on each leg, and the output charged by the recipe’s success chance |
| I22 | Every trade in the catalogue is staffed or explicitly unstaffed with a reason |
| I14 | step(step(x, a), b) == step(x, a + b) — what makes lazy catch-up and the global tick the same thing |
| I15 | A single step is clamped to thirty game-days |
I21 is the one to write first. It is the single check that stops the crafting tree being a gold printer. It compares prices inside one town, not across the 0.5× to 4× band: buying where a good is cheap and selling where it is dear is hauling, which is intended play, and settling unit by unit against the live price closes the gap by itself. Measured across the band, every recipe worth crafting would be a printer, and no recipe could have both ends priced.
Behaviour
| # | Invariant |
|---|---|
| I16 | A thousand undisturbed game-days leave a settlement at its reference |
| I17 | A settlement driven empty and then left alone returns to within 5% in sixty game-days |
| I18 | A player standing in a town, not trading, changes nothing |
| I19 | Damage is monotone — more destruction never raises a capacity |
| I20 | Per-channel loss ceilings: burnt ground and felled woods may each take at most 60% of capacity, destroyed workplaces 80% |
I17 is the no-dead-world proof. I20 is better than a floor on overall health because it is per-channel and explicable to a player: a perfect siege leaves a town wretched, not dead. The felling ceiling matters most, because a wood cut to the last tree never grows back.
Degradation, and why recovery is unconditional
Runtime never edits population, the trade roster or the building count. Those belong to the generator, and the moment the runtime writes them there are two disagreeing world models. Instead, in order: price rises to its ceiling; imports surge if the roads and the money exist; a hunger factor throttles non-food capacity only, so workers are hungry and workshops idle while bread is still baked; and a distress flag makes the state legible to GM tooling and to dialog, which reads a town’s condition as something its people can be asked about.
There is no absorbing state, because every damage channel recovers on something a player cannot suppress:
- Scorched ground heals on rain, not on a timer.
- Props regrow on their own deadline.
- Buildings are rebuilt out of the treasury.
So health returns to full in bounded time from any state, and by I17 the ledger follows.
What an adversary does
| Attack | What stops it |
|---|---|
| Buy out every shop | I12 — only the surplus above the local reserve is on offer. This is also just what a caravan does |
| Dump ten thousand apples | I4 and I8, by refusal rather than a bad price: the warehouse fills, or the purse runs out |
| Camp a farm and burn it forever | It should work — a siege should work. Bounded by I20’s ceiling, by the fire system’s own limits, and by the camper having to physically spread out over a 7–20 km catchment |
| Arbitrage two towns | Spread at both ends, plus settling unit by unit against the live price function, never a snapshot, so the marginal prices converge and the arbitrage extinguishes itself |
| Craft money out of NPC goods | I21 |
Arbitrage is intended gameplay, not an exploit: the player is the caravan, and closing a price gap is what a merchant is for. Two supporting rules make it work rather than dominate. Carrying capacity bounds the volume per trip. And there is no global price oracle — a client only ever learns the prices of the settlement it is standing in, because a world where every price is visible at once turns the merchant profession into a spreadsheet.
One hole worth stating rather than papering over: the economy is only as bounded as the item faucets feeding it, and monster loot is currently unbounded. A per-commodity daily absorption budget fixes it, but that is a separate decision.
Consistency between the tiers
The ledger is the only producer, always. The visible baker never produces anything — a baking animation renders production the ledger has already accounted for.
This is the only design that satisfies “a watched town produces the same as an unwatched one” without heroics. The alternative requires a continuous model and a sequence of interruptible animations to agree numerically, and they never will, because the animation gets cut off when the player walks away mid-loaf.
A shop is a transient projection, not a container. It is derived on spawn as
min(offerable, displayCap) and nothing is written back — so there is no despawn path, no
reconciliation, and no “shop vanished holding items” bug.
Purchases go through an intent component resolved by a system, mirroring how prop collection already resolves a race between two players reaching for the same herb. Two players buying the last loaf are visited by a single pass; the first decrements the in-memory ledger synchronously and the second is refused. Entity operations defer to the end of the tick and would grant twice.
If the server dies mid-purchase, fail in the player’s favour, and write that down. The item is granted through the durable path; the ledger side rides the periodic snapshot, so the worst case is under a minute of one settlement’s trades replayed as though they had not happened — invisible, and self-correcting because prices reconverge. The coin side must not ride the snapshot: coin is the scarce thing, and duplicating it is the one duplication that matters.
Townsfolk AI
The GOAP domain that gives townsfolk their occupations and daily schedules, their homes and workplaces, and the level of detail that decides which of them exist as agents, is on Townsfolk AI.
Where it plugs into the engine
| System | Cadence | Notes |
|---|---|---|
| Shop trade intent | Every tick | Immediately before prop collection, which it mirrors |
| Settlement economy | Every 60 s | After the divergence writers, so damage from this tick is already visible |
| Townsfolk residency | Every second | Declares no AI-agent write; entity creation defers to end of tick |
The economy system declares empty read and write sets, and that has to be earned rather than asserted: it touches only non-ECS services and must never mutate a component. The scorch regrowth system carries the warning to repeat here — an earlier version declared a write it did not make, purely to force an ordering, and “that worked and cost far too much: an always-present system conflicting with a large part of the engine flattens the wave scheduling for everything”.
Because the step takes elapsed game days rather than a frame delta, a global tick and lazy catch-up on read are the same computation, guaranteed by I14. The global tick is still worth having: it is what makes distant towns move, so a player arriving somewhere new finds a world that has been living.
Known blockers
Two of these are live bugs in shipped code and must be fixed before any of this works.
- A destroyed building never comes back — on any future boot. No building kind has a regrowth time, so destruction writes a permanent divergence and the world quietly loses a mill for good. The fix is not a regrow timer: the economy step pays for a rebuild out of the treasury, so a rich city rebuilds in a day, a poor hamlet takes a season, and a hamlet whose treasury a player keeps draining stays a ruin. A building should come back because the town can afford it, not because a clock ran out.
- Every AI belief silently expires after ten real minutes — thirty in-game minutes. The drive system dodges this by marking each write permanent by hand, but an action’s effect has no such call site, so any day-scale belief evaporates and the NPC goes back to work. State keys need to carry their own retention.
- There is no humanoid NPC visual. The wire’s visual kinds are creature, item and effect, so a townsfolk is a creature-visual entry until there is a reason it cannot be.
- Building the townsfolk through the creature spawner would persist them. It marks entities persistent unconditionally, and the mob persister matches anything with a creature visual and no account — so a city’s worth of townsfolk would be written to the database and rehydrated at boot as ownerless mobs, growing every restart. A separate spawner, sharing the component set.
- Sixteen of the thirty-three trades cannot produce anything until their goods are priced.
- Ore deposits cannot be exhausted — no prop and no identity; carved voxels are saved, a deposit is not.
- Monster loot is an unbounded item faucet, and the economy is only as bounded as its faucets.
Last updated 04 Dec 2026, 01:08 +0100 .