Skip to content

A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D

Town simulation: roads, walkers, homes, production chains, taxes and trade

SandroMaglione2999905a8102
diff --git a/README.md b/README.md
index 4383b53..5be8148 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,9 @@
-# Factory yard
+# Town
-A prototype: place line-drawn isometric factories on a grid, connect them
-with conveyor belts, and watch crates flow. Game logic runs on the
-[bevy-ts](../../bevy-ts) ECS; Pixi draws it.
+A town simulation in the spirit of Anno, drawn in pale isometric line art:
+lay roads, house settlers, gather and craft goods, keep homes supplied, and
+grow settlers into citizens. Game logic runs on the [bevy-ts](../../bevy-ts)
+ECS; Pixi draws it.
```sh
pnpm install
@@ -10,11 +11,65 @@ pnpm dev --host --port 5232
pnpm typecheck
```
-The bevy-ts packages are linked from `../../bevy-ts` and consumed as source.
+The bevy-ts packages are linked from `../../bevy-ts` and consumed as source,
+so clone [bevy-ts](https://github.com/SandroMaglione/bevy-ts) two levels up
+first (for example `gamedev/bevy-ts` next to `gamedev/games/inkline-town`).
+
+## How the town works
+
+- **A new town** is generated land (a lake, forests, stone and ore) with a
+ town hall in a clearing, ringed by road, plus starting coins and goods.
+- **Coins**: homes the town hall can reach by road pay taxes; traders buy
+ the goods the town chooses to sell beyond a reserve; every building costs
+ upkeep. Building costs coins up front. The **town** panel (T, or click the
+ top bar) shows the treasury, people, supplies, and goods over time, and
+ holds the levers: a tax rate per tier (high taxes shrink homes), which
+ goods to sell, and how much to keep.
+- **Materials** (planks, stone, tools) come from storage: a new building is a
+ site until carriers have brought what it costs, then it goes up.
+- **Homes** fill with settlers once a road touches them. Settlers need food
+ (fish or bread); with bread, cloth, and faith a home becomes a two-story
+ citizens' home that holds and pays twice as much.
+- **Buildings** need a road at the middle of a side and workers from the
+ homes. Gatherers work the land within their reach (trees, rocks, water,
+ fields); workshops turn one good into another.
+- **Carriers** walk every good along the roads: producers send to whoever
+ wants it (a site, a workshop, a market) or else to storage; storage sends
+ to whoever wants what it holds.
+- **Walkers** from the town hall and markets hand out food and cloth to the
+ homes they pass; the chapel's brings faith.
+- Larger buildings unlock as the town grows (by residents, then citizens).
+
+## Code
- `src/iso.ts`: the grid and the unit everything is measured in (1/16 cell = 2×1 px).
-- `src/kinds.ts`: the factory kinds and their sizes.
-- `src/route.ts`: belt pathfinding.
-- `src/schema.ts`, `src/systems.ts`: the ECS world and its systems.
+- `src/content.ts`: goods, building kinds, home tiers, costs, upkeep, taxes: plain data.
+- `src/archetypes.ts`: content to components.
+- `src/mapgen.ts`: the land of a new town, from a seed.
+- `src/schema.ts`: the ECS world: components, relations, resources, services.
+- `src/grid.ts`: occupancy, entrances, reach, and road paths.
+- `src/sim/`: the fixed-step simulation (no renderer access): edits, work, logistics, walkers, town.
+- `src/present.ts`: per-frame interaction, panel, and view sync.
- `src/art.ts`: all drawing.
-- `src/host.ts`, `src/main.ts`: the page, camera, input, panel, and start-up.
+- `src/ui.ts`, `src/host.ts`, `src/main.ts`: the page bridge, camera, input, panels, and start-up.
+
+The simulation runs on bevy-ts-browser's `FixedLoop` at 60 steps a second,
+with integer state and a seeded random resource. Every saved component is
+validated, so **save** / **load** snapshot the whole world to localStorage.
+
+In development the console has `town.ui`, `town.runtime`, and
+`town.advance(seconds)` to fast-forward the simulation.
+
+## Balancing
+
+`pnpm balance` runs a bot that plays the real simulation headless, the way a
+sensible player would, on several seeds, and summarises how the towns did:
+residents, coins and where they came from, when citizens first appeared, how
+well homes were supplied, and which buildings were stuck and why.
+
+```sh
+pnpm balance -- --seeds 10 --minutes 45
+pnpm balance -- --tax 150
+pnpm balance -- --set kinds.fishery.recipe.seconds=3 --set home.tiers.1.tax=2
+pnpm balance -- --seeds 1 --verbose # minute by minute, what was built, what was left
+```
diff --git a/index.html b/index.html
index 4989291..ae9f063 100644
--- a/index.html
+++ b/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
- <title>Factory · isometric belts</title>
+ <title>Town</title>
<link rel="stylesheet" href="/src/factory.css" />
</head>
<body>
diff --git a/package.json b/package.json
index 6a793be..2ed49e6 100644
--- a/package.json
+++ b/package.json
@@ -6,10 +6,13 @@
"scripts": {
"dev": "vite",
"build": "vite build",
- "typecheck": "tsc -p tsconfig.json --pretty false"
+ "typecheck": "tsc -p tsconfig.json --pretty false",
+ "balance": "node scripts/balance.ts"
},
"dependencies": {
"@typeonce/bevy-ts": "link:../../bevy-ts/packages/core",
+ "@typeonce/bevy-ts-browser": "link:../../bevy-ts/packages/browser",
+ "@typeonce/bevy-ts-math": "link:../../bevy-ts/packages/math",
"@typeonce/bevy-ts-pixi": "link:../../bevy-ts/packages/pixi",
"@typeonce/bevy-ts-render": "link:../../bevy-ts/packages/render",
"pixi.js": "^8.22.0"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e73c9ae..3f4a844 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -11,6 +11,12 @@ importers:
'@typeonce/bevy-ts':
specifier: link:../../bevy-ts/packages/core
version: link:../../bevy-ts/packages/core
+ '@typeonce/bevy-ts-browser':
+ specifier: link:../../bevy-ts/packages/browser
+ version: link:../../bevy-ts/packages/browser
+ '@typeonce/bevy-ts-math':
+ specifier: link:../../bevy-ts/packages/math
+ version: link:../../bevy-ts/packages/math
'@typeonce/bevy-ts-pixi':
specifier: link:../../bevy-ts/packages/pixi
version: link:../../bevy-ts/packages/pixi
diff --git a/scripts/balance.ts b/scripts/balance.ts
new file mode 100644
index 0000000..04289f9
--- /dev/null
+++ b/scripts/balance.ts
@@ -0,0 +1,364 @@
+/**
+ * Balance runs: a bot plays the real simulation headless, the way a
+ * sensible player would, on several seeds, and reports how the town does
+ * minute by minute and where it got stuck.
+ *
+ * node scripts/balance.ts 5 seeds, 30 minutes each
+ * node scripts/balance.ts --seeds 10 --minutes 45
+ * node scripts/balance.ts --tax 125 settlers and citizens taxed at 125%
+ * node scripts/balance.ts --set kinds.fishery.recipe.seconds=3 --set home.tiers.1.tax=3
+ * node scripts/balance.ts --verbose print every seed's minute-by-minute table
+ *
+ * `--set` changes content before the run (any number of them), so a sweep is
+ * a shell loop over values. The bot only does what a player could: it reads
+ * the world, then pushes the same edits the page does.
+ */
+import { amounts, goodIds, home, kinds, ROAD_COST, start, STEP_SECONDS, total, type Amounts, type Kind, type KindId } from "../src/content.ts"
+import { around, canPlace, DIRS, entrances, GridBuilder, isRoad, key, useAt, type Use } from "../src/grid.ts"
+import { GRID, inside, type Point } from "../src/iso.ts"
+import { Game, Ui, type GridValue } from "../src/schema.ts"
+import { simulate } from "../src/sim/index.ts"
+import { emptyPreview, type Edit, type UiValue } from "../src/ui.ts"
+
+// ── Options ───────────────────────────────────────────────────────────────
+
+const args = process.argv.slice(2)
+const option = (name: string, fallback: number) => {
+ const i = args.indexOf(`--${name}`)
+ return i >= 0 ? Number(args[i + 1]) : fallback
+}
+const seeds = option("seeds", 5)
+const minutes = option("minutes", 30)
+const tax = option("tax", 100)
+const verbose = args.includes("--verbose")
+
+/** `--set path=value`: change a number in the content before running. */
+const roots: Record<string, unknown> = { kinds, home, start }
+for (let i = 0; i < args.length; i++) {
+ if (args[i] !== "--set") continue
+ const [path, value] = args[i + 1]!.split("=")
+ const parts = path!.split(".")
+ let target = roots as Record<string, unknown>
+ for (const part of parts.slice(0, -1)) target = target[part] as Record<string, unknown>
+ target[parts.at(-1)!] = Number(value)
+}
+
+// ── Reading the world ─────────────────────────────────────────────────────
+
+interface Snapshot {
+ readonly entities: ReadonlyArray<{ readonly id: number; readonly components: Record<string, any> }>
+ readonly resources: Record<string, any>
+}
+
+interface World {
+ readonly grid: GridValue
+ /** Cells of ore rocks (other rocks are stone). */
+ readonly ore: ReadonlySet<number>
+ readonly buildings: ReadonlyArray<{ readonly kind: KindId; readonly tile: Tile; readonly status: string; readonly site: boolean }>
+ readonly homes: ReadonlyArray<{ readonly tile: Tile; readonly tier: number; readonly residents: number }>
+ readonly stock: Amounts
+ readonly coins: number
+ readonly census: Record<string, number>
+ readonly ledger: { readonly taxes: number; readonly trade: number; readonly upkeep: number }
+}
+interface Tile {
+ readonly x: number
+ readonly y: number
+ readonly size: number
+}
+
+const read = (snapshot: Snapshot): World => {
+ const builder = new GridBuilder()
+ const buildings: Array<World["buildings"][number]> = []
+ const homes: Array<World["homes"][number]> = []
+ const stock: Record<string, number> = { ...amounts({}) }
+ const ore = new Set<number>()
+ for (const e of snapshot.entities) {
+ const c = e.components
+ const tile = c["Town/Tile"] as Tile | undefined
+ if (!tile) continue
+ const use: Use = c["Town/Road"] ? "road" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : "building"
+ builder.claim(tile, e.id, use)
+ if (c["Town/Rock"]?.ore) ore.add(key(tile.x, tile.y))
+ if (c["Town/Building"]) buildings.push({ kind: c["Town/Building"].kind, tile, status: c["Town/Status"], site: !!c["Town/Site"] })
+ if (c["Town/House"]) homes.push({ tile, tier: c["Town/House"].tier, residents: c["Town/House"].residents })
+ if (c["Town/Storage"] && c["Town/Inventory"]) for (const g of goodIds) stock[g] = (stock[g] ?? 0) + c["Town/Inventory"].stock[g]
+ }
+ return {
+ grid: builder.value(),
+ ore,
+ buildings,
+ homes,
+ stock: stock as Amounts,
+ coins: snapshot.resources["Town/Treasury"].coins,
+ census: snapshot.resources["Town/Census"],
+ ledger: snapshot.resources["Town/Ledger"]
+ }
+}
+
+// ── The bot ───────────────────────────────────────────────────────────────
+
+const affordable = (w: World, cost: Kind["cost"]) =>
+ w.coins >= cost.coins + 40 && Object.entries(cost.materials).every(([g, n]) => w.stock[g as keyof Amounts] >= (n ?? 0))
+const residents = (w: World) => w.census.settlers! + w.census.citizens!
+const unlocked = (w: World, kind: Kind) => residents(w) >= kind.unlock.residents && w.census.citizens! >= kind.unlock.citizens
+const count = (w: World, kind: KindId) => w.buildings.filter((b) => b.kind === kind).length
+const sites = (w: World) => w.buildings.filter((b) => b.site).length + 0
+
+const sourceUse: Record<string, Use> = { tree: "tree", stone: "rock", ore: "rock", water: "water", field: "empty" }
+
+/** How good a spot is for a kind: how much of what it works lies within reach (or 1 for anything else). */
+const score = (w: World, kind: Kind, tile: Tile): number => {
+ const g = kind.gathers ?? (kind.plants ? { source: kind.plants.what === "tree" ? "field" : "field", radius: kind.plants.radius } : null)
+ if (!g) return 1
+ const want = sourceUse[g.source]!
+ return around(tile, g.radius).filter((c) => useAt(w.grid, c.x, c.y) === want && (want !== "rock" || w.ore.has(key(c.x, c.y)) === (g.source === "ore"))).length
+}
+
+/** Where to put a kind: road at a door, room for it, and (for gatherers) the most to work, nearest the middle as a tiebreak. */
+const spotFor = (w: World, kind: Kind): Point | null => {
+ let best: { cell: Point; value: number } | null = null
+ const needs = kind.gathers ? (kind.gathers.source === "tree" ? 8 : kind.gathers.source === "water" ? 2 : kind.gathers.source === "field" ? 0 : 2) : 0
+ for (let y = 0; y + kind.size <= GRID; y++) {
+ for (let x = 0; x + kind.size <= GRID; x++) {
+ const tile = { x, y, size: kind.size }
+ if (!canPlace(w.grid, tile)) continue
+ if (!entrances(tile).some((c) => isRoad(w.grid, c.x, c.y))) continue
+ const s = score(w, kind, tile)
+ if (s < needs) continue
+ // A forester belongs beside a lumberjack, replanting what it fells.
+ if (kind.id === "forester" && !w.buildings.some((b) => b.kind === "lumberjack" && Math.abs(b.tile.x - x) <= 4 && Math.abs(b.tile.y - y) <= 4)) continue
+ const value = (kind.gathers || kind.plants ? s * 10 : 0) - Math.hypot(x - GRID / 2, y - GRID / 2)
+ if (!best || value > best.value) best = { cell: { x, y }, value }
+ }
+ }
+ return best?.cell ?? null
+}
+
+/** Free cells beside a road, nearest the middle first. */
+const homeSpots = (w: World, n: number): Array<Point> => {
+ const spots: Array<Point> = []
+ for (let y = 0; y < GRID; y++) {
+ for (let x = 0; x < GRID; x++) {
+ if (useAt(w.grid, x, y) !== "empty") continue
+ if (DIRS.some((d) => isRoad(w.grid, x + d.x, y + d.y))) spots.push({ x, y })
+ }
+ }
+ return spots.sort((a, b) => Math.hypot(a.x - GRID / 2, a.y - GRID / 2) - Math.hypot(b.x - GRID / 2, b.y - GRID / 2)).slice(0, n)
+}
+
+/**
+ * A road towards what a kind needs (or, for anything else, into open land):
+ * the shortest run of free cells from the road network to a cell near the
+ * source, at most `limit` long.
+ */
+const roadToward = (w: World, kind: Kind | null, limit = 10): Array<Point> => {
+ const free = (x: number, y: number) => inside(x, y) && (useAt(w.grid, x, y) === "empty" || useAt(w.grid, x, y) === "tree")
+ const want = kind?.gathers ? sourceUse[kind.gathers.source] : null
+ const goal = (x: number, y: number) =>
+ want ? DIRS.some((d) => useAt(w.grid, x + 2 * d.x, y + 2 * d.y) === want || useAt(w.grid, x + 3 * d.x, y + 3 * d.y) === want) : around({ x, y, size: 1 }, 2).every((c) => free(c.x, c.y))
+ const previous = new Map<number, number>()
+ const queue: Array<Point> = []
+ for (let y = 0; y < GRID; y++) for (let x = 0; x < GRID; x++) if (isRoad(w.grid, x, y)) queue.push({ x, y })
+ const seen = new Set(queue.map((c) => key(c.x, c.y)))
+ const depth = new Map(queue.map((c) => [key(c.x, c.y), 0]))
+ for (let head = 0; head < queue.length; head++) {
+ const c = queue[head]!
+ const d = depth.get(key(c.x, c.y))!
+ if (d > 0 && goal(c.x, c.y)) {
+ const path: Array<Point> = []
+ for (let k: number | undefined = key(c.x, c.y); k !== undefined && !isRoad(w.grid, k % GRID, Math.floor(k / GRID)); k = previous.get(k)) path.push({ x: k % GRID, y: Math.floor(k / GRID) })
+ return path.reverse()
+ }
+ if (d >= limit) continue
+ for (const dir of DIRS) {
+ const n = { x: c.x + dir.x, y: c.y + dir.y }
+ const k = key(n.x, n.y)
+ if (seen.has(k) || !free(n.x, n.y)) continue
+ seen.add(k)
+ previous.set(k, key(c.x, c.y))
+ depth.set(k, d + 1)
+ queue.push(n)
+ }
+ }
+ return []
+}
+
+/** What the bot wants next, in order: the first it can do, it does. */
+const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: boolean }> => {
+ const homes = w.homes.length
+ const fed = homes > 0 ? w.census.food! / homes : 1
+ return [
+ { kind: "fishery", when: count(w, "fishery") < 1 },
+ { kind: "lumberjack", when: count(w, "lumberjack") < 1 },
+ { kind: "sawmill", when: count(w, "sawmill") < 1 },
+ { kind: "quarry", when: count(w, "quarry") < 1 },
+ { kind: "market", when: count(w, "market") < 1 && homes >= 6 },
+ { kind: "forester", when: count(w, "forester") < count(w, "lumberjack") },
+ { kind: "fishery", when: fed < 0.6 && count(w, "fishery") < 1 + Math.floor(homes / 10) },
+ { kind: "chapel", when: count(w, "chapel") < 1 },
+ { kind: "sheep", when: count(w, "sheep") < 1 },
+ { kind: "weaver", when: count(w, "weaver") < 1 },
+ { kind: "farm", when: count(w, "farm") < 1 },
+ { kind: "mill", when: count(w, "mill") < 1 },
+ { kind: "bakery", when: count(w, "bakery") < 1 },
+ { kind: "market", when: fed < 0.6 && count(w, "market") < Math.floor(homes / 12) + 1 },
+ { kind: "lumberjack", when: w.stock.planks < 10 && count(w, "lumberjack") < 3 },
+ { kind: "quarry", when: w.stock.stone < 6 && count(w, "quarry") < 3 },
+ { kind: "warehouse", when: count(w, "warehouse") < Math.floor(homes / 20) },
+ { kind: "mine", when: count(w, "mine") < 1 },
+ { kind: "smithy", when: count(w, "smithy") < 1 }
+ ]
+}
+
+/** One decision: build what is wanted first, or homes when workers run short, or road towards what is needed. */
+const decide = (w: World): ReadonlyArray<Edit> => {
+ if (sites(w) > 2) return []
+ // Homes when workers run short, or (they are the town's income) whenever food reaches most of them.
+ const fed = w.homes.length > 0 ? w.census.food! / w.homes.length : 1
+ const short = w.census.jobs! + 6 > residents(w) || (fed >= 0.7 && w.stock.planks >= 8)
+ if (short && affordable(w, { coins: home.cost.coins * 3, materials: { planks: 3 } })) {
+ const spots = homeSpots(w, 3)
+ if (spots.length > 0) return [{ type: "homes", cells: spots }]
+ const road = roadToward(w, null)
+ if (road.length > 0 && w.coins > road.length * ROAD_COST + 60) return [{ type: "roads", cells: road }]
+ }
+ for (const want of plan(w)) {
+ if (!want.when) continue
+ const kind = kinds[want.kind]
+ if (!unlocked(w, kind) || !affordable(w, kind.cost)) continue
+ const spot = spotFor(w, kind)
+ if (spot) return [{ type: "building", kind: want.kind, cell: spot, open: false }]
+ const road = roadToward(w, kind)
+ if (road.length > 0 && w.coins > road.length * ROAD_COST + kind.cost.coins) return [{ type: "roads", cells: road }]
+ }
+ return []
+}
+
+// ── Running ───────────────────────────────────────────────────────────────
+
+interface Row {
+ readonly minute: number
+ readonly coins: number
+ readonly net: number
+ readonly taxes: number
+ readonly trade: number
+ readonly upkeep: number
+ readonly settlers: number
+ readonly citizens: number
+ readonly homes: number
+ readonly food: number
+ readonly cloth: number
+ readonly faith: number
+ readonly jobs: string
+ readonly buildings: number
+ readonly problems: Record<string, number>
+}
+
+const run = (seed: number) => {
+ const ui: UiValue = {
+ tool: "select", placing: null, menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],
+ edits: [{ type: "newTown", seed }],
+ preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, toast: () => {}
+ }
+ const made = Game.Runtime.make({
+ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)),
+ resources: {
+ Time: { tick: 0 }, Rng: seed, Treasury: { coins: 0 }, Ledger: { taxes: 0, trade: 0, upkeep: 0 },
+ Census: { homes: 0, settlers: 0, citizens: 0, jobs: 0, employed: 0, food: 0, bread: 0, cloth: 0, faith: 0 },
+ Policy: { settlers: 100, citizens: 100, sells: [], reserve: 25 }, Grid: { owner: [], use: [] }, Stock: amounts({})
+ }
+ })
+ if (!made.ok) throw new Error(JSON.stringify(made.error))
+ const runtime = made.value
+ const step = (seconds: number) => {
+ for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)
+ }
+ step(0.1)
+ // The new town has its usual policy; set the taxes for this run.
+ ui.edits.push({ type: "tax", tier: "settlers", rate: tax }, { type: "tax", tier: "citizens", rate: tax })
+ step(0.1)
+
+ const rows: Array<Row> = []
+ const problems: Record<string, number> = {}
+ let firstCitizen: number | null = null
+ let minCoins = Infinity
+ let debtMinutes = 0
+ const DECIDE = 5
+ for (let t = 0; t < minutes * 60; t += DECIDE) {
+ const w = read(runtime.snapshot() as unknown as Snapshot)
+ ui.edits.push(...decide(w))
+ step(DECIDE)
+ minCoins = Math.min(minCoins, w.coins)
+ if ((t + DECIDE) % 60 === 0) {
+ const now = read(runtime.snapshot() as unknown as Snapshot)
+ const minute = (t + DECIDE) / 60
+ const problemsNow: Record<string, number> = {}
+ for (const b of now.buildings) {
+ if (["unconnected", "unstaffed", "starved", "blocked"].includes(b.status) && !b.site) {
+ const k = `${b.kind} ${b.status}`
+ problemsNow[k] = (problemsNow[k] ?? 0) + 1
+ problems[k] = (problems[k] ?? 0) + 1
+ }
+ }
+ if (now.coins < 0) debtMinutes += 1
+ if (firstCitizen === null && now.census.citizens! > 0) firstCitizen = minute
+ const h = Math.max(1, now.homes.length)
+ rows.push({
+ minute,
+ coins: now.coins,
+ net: now.ledger.taxes + now.ledger.trade - now.ledger.upkeep,
+ taxes: now.ledger.taxes,
+ trade: now.ledger.trade,
+ upkeep: now.ledger.upkeep,
+ settlers: now.census.settlers!,
+ citizens: now.census.citizens!,
+ homes: now.homes.length,
+ food: Math.round((now.census.food! / h) * 100),
+ cloth: Math.round((now.census.cloth! / h) * 100),
+ faith: Math.round((now.census.faith! / h) * 100),
+ jobs: `${now.census.employed}/${now.census.jobs}`,
+ buildings: now.buildings.length,
+ problems: problemsNow
+ })
+ }
+ }
+ const end = read(runtime.snapshot() as unknown as Snapshot)
+ const built: Record<string, number> = {}
+ for (const b of end.buildings) built[b.kind] = (built[b.kind] ?? 0) + 1
+ return { seed, rows, problems, firstCitizen, minCoins, debtMinutes, built, stock: end.stock }
+}
+
+const pad = (v: unknown, n: number) => String(v).padStart(n)
+const results = []
+const started = performance.now()
+for (let i = 0; i < seeds; i++) {
+ const r = run(1000 + i * 7919)
+ results.push(r)
+ if (verbose) {
+ console.log(`\nseed ${r.seed}`)
+ console.log(" min coins net settlers citizens homes food% cloth% faith% jobs bldgs problems")
+ for (const row of r.rows) {
+ const p = Object.entries(row.problems).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")
+ console.log(`${pad(row.minute, 4)} ${pad(row.coins, 7)} ${pad(row.net, 5)} ${pad(row.settlers, 9)} ${pad(row.citizens, 8)} ${pad(row.homes, 5)} ${pad(row.food, 5)} ${pad(row.cloth, 6)} ${pad(row.faith, 6)} ${pad(row.jobs, 7)} ${pad(row.buildings, 6)} ${p}`)
+ }
+ console.log(` built: ${Object.entries(r.built).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")}`)
+ console.log(` stock: ${goodIds.filter((g) => r.stock[g] > 0).map((g) => `${g} ${r.stock[g]}`).join(", ")}`)
+ }
+}
+
+// ── Summary ───────────────────────────────────────────────────────────────
+
+const mean = (xs: ReadonlyArray<number>) => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
+const last = results.map((r) => r.rows.at(-1)!)
+console.log(`\n${seeds} seeds × ${minutes} min, tax ${tax}% (${Math.round(performance.now() - started)} ms)`)
+console.log(` residents at the end ${mean(last.map((r) => r.settlers + r.citizens)).toFixed(0)} (citizens ${mean(last.map((r) => r.citizens)).toFixed(0)})`)
+console.log(` coins at the end ${mean(last.map((r) => r.coins)).toFixed(0)}, net ${mean(last.map((r) => r.net)).toFixed(0)}/min (taxes ${mean(last.map((r) => r.taxes)).toFixed(0)}, trade ${mean(last.map((r) => r.trade)).toFixed(0)}, upkeep ${mean(last.map((r) => r.upkeep)).toFixed(0)})`)
+console.log(` lowest coins ${Math.min(...results.map((r) => r.minCoins))} minutes in debt ${mean(results.map((r) => r.debtMinutes)).toFixed(1)}`)
+console.log(` first citizens ${results.map((r) => (r.firstCitizen === null ? "never" : `${r.firstCitizen} min`)).join(", ")}`)
+console.log(` homes supplied food ${mean(last.map((r) => r.food)).toFixed(0)}%, cloth ${mean(last.map((r) => r.cloth)).toFixed(0)}%, faith ${mean(last.map((r) => r.faith)).toFixed(0)}%`)
+const allProblems: Record<string, number> = {}
+for (const r of results) for (const [k, n] of Object.entries(r.problems)) allProblems[k] = (allProblems[k] ?? 0) + n
+const top = Object.entries(allProblems).sort((a, b) => b[1] - a[1]).slice(0, 6)
+console.log(` most common problems ${top.map(([k, n]) => `${k} (${(n / seeds).toFixed(1)} min/seed)`).join(", ") || "none"}`)
+void total
diff --git a/src/archetypes.ts b/src/archetypes.ts
new file mode 100644
index 0000000..a66cd63
--- /dev/null
+++ b/src/archetypes.ts
@@ -0,0 +1,72 @@
+/**
+ * Content to components: how each thing in `content.ts` is assembled from
+ * the schema's components. A building is a `Tile`, a `Building`, a `Status`,
+ * `Staff`, and one component for each role its kind has. Anything that
+ * costs materials starts as a `Site`, anything else starts `Rising`; the
+ * land is a `Tile` and its own marker.
+ */
+import { amounts, goodIds, home, total, type Kind } from "./content.ts"
+import type { Point } from "./iso.ts"
+import {
+ Building, Carriers, Field, Game, Gatherer, House, Inventory, Planter, Recipe, Rising, Road, Rock, Service, Site, Staff,
+ Status, Storage, Tile, Tree, Water
+} from "./schema.ts"
+import { ticks } from "./content.ts"
+
+const site = (cost: Kind["cost"]) => {
+ const owed = amounts(cost.materials)
+ return total(owed) > 0 ? Game.Command.entry(Site, { owed, total: total(owed) }) : Game.Command.entry(Rising, { ticks: 0 })
+}
+
+/** A building of `kind` on `cell`: a site waiting for materials, or (`standing`) already up. */
+export const buildingDraft = (kind: Kind, cell: Point) =>
+ Game.Command.spawn(
+ [Tile, { x: cell.x, y: cell.y, size: kind.size }],
+ [Building, { kind: kind.id }],
+ [Status, "building"],
+ [Staff, { needed: kind.workers, assigned: 0 }]
+ )
+
+/** How a new building starts: owed its materials, or rising straight away. */
+export const startOf = (kind: Kind) => site(kind.cost)
+
+/** The role components a kind's buildings carry, inserted after the building is spawned. */
+export const rolesOf = (kind: Kind) => {
+ const roles = []
+ if (kind.recipe) {
+ const r = kind.recipe
+ roles.push(Game.Command.entry(Recipe, { input: r.input, inputs: r.inputs, output: r.output, batch: r.batch, period: ticks(r.seconds), progress: 0, made: 0 }))
+ }
+ if (kind.gathers) roles.push(Game.Command.entry(Gatherer, { source: kind.gathers.source, radius: kind.gathers.radius }))
+ if (kind.plants) {
+ const p = kind.plants
+ roles.push(Game.Command.entry(Planter, { what: p.what, radius: p.radius, interval: ticks(p.seconds), cooldown: 0, max: p.max }))
+ }
+ if (kind.holds) {
+ const all = kind.holds.accepts === "all"
+ roles.push(Game.Command.entry(Inventory, { stock: amounts({}), accepts: all ? goodIds : kind.holds.accepts, cap: kind.holds.cap }))
+ if (all) roles.push(Game.Command.entry(Storage, {}))
+ } else if (kind.recipe) {
+ // A gatherer keeps what it makes until a carrier takes it.
+ roles.push(Game.Command.entry(Inventory, { stock: amounts({}), accepts: [kind.recipe.output], cap: 8 }))
+ }
+ if (kind.carriers) roles.push(Game.Command.entry(Carriers, { count: kind.carriers }))
+ if (kind.service) {
+ const s = kind.service
+ roles.push(Game.Command.entry(Service, { service: s.service, interval: ticks(s.seconds), cooldown: 0, range: s.range }))
+ }
+ return roles
+}
+
+export const houseDraft = (cell: Point) =>
+ Game.Command.spawn(
+ [Tile, { x: cell.x, y: cell.y, size: 1 }],
+ [House, { tier: 1, residents: 0, food: 0, bread: 0, cloth: 0, faith: 0, clock: 0 }]
+ )
+export const houseStart = () => site(home.cost)
+
+export const roadDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Road, {}])
+export const treeDraft = (cell: Point, growth: number) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Tree, { growth }])
+export const rockDraft = (cell: Point, ore: boolean, amount: number) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Rock, { ore, amount }])
+export const waterDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Water, {}])
+export const fieldDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Field, { growth: 0 }])
diff --git a/src/art.ts b/src/art.ts
index 33288cd..999806f 100644
--- a/src/art.ts
+++ b/src/art.ts
@@ -1,57 +1,73 @@
/**
- * The yard's look: pale line-drawn buildings on plates, hatched conveyor
- * belts with square joints, cardboard crates with coloured labels, and
- * monospace name tags. Everything is drawn with Pixi graphics in world
- * pixels, measured in units (see `iso.ts`): floor lengths are whole units,
- * heights whole pixels, and lines one of two weights.
+ * The town's look: pale line-drawn buildings and homes on plates, paved
+ * roads with square joints, trees, rocks, fields and water drawn in the same
+ * ink, cardboard crates with coloured labels, and small walkers. Everything
+ * is drawn with Pixi graphics in world pixels, measured in units (see
+ * `iso.ts`): floor lengths are whole units, heights whole pixels, and lines
+ * one of two weights.
+ *
+ * Colour is kept for meaning: awnings by what a building is for, crate
+ * labels by good, a home's door, the red of a problem marker.
*
* The measures that have to agree:
- * - a belt is 8 units wide and runs down the middle of a cell;
- * - it meets a factory at the middle of a side, where a door 10 units wide
- * (the belt and a unit of frame either side) stands centred on it;
- * - a crate is 6 units wide: a unit of belt shows either side;
- * - a factory's 3×3 plate is a unit inside its footprint.
+ * - a road is 12 units wide and runs down the middle of a cell;
+ * - a building's door is 10 units wide, centred on a side where a road
+ * meets it;
+ * - a plate is a unit inside its footprint;
+ * - a crate is 6 units wide, a carried one 4.
*/
-import { Container, Graphics, Text, TextStyle } from "pixi.js"
+import { Container, Graphics } from "pixi.js"
-import { flat, FOOTPRINT, GRID, toScreen, U, type Point } from "./iso.ts"
-import { kinds, type Kind, type KindId } from "./kinds.ts"
-import type { Status, WorkValue } from "./schema.ts"
+import { categoryColor, GROWN, home, kinds, ROCK_AMOUNT, type Kind, type KindId, type Tier } from "./content.ts"
+import { cellOf, DIRS, key } from "./grid.ts"
+import { flat, GRID, toScreen, U, type Point } from "./iso.ts"
export const ink = 0x3d4943
const plateFill = 0xf5f6f2
const roofFill = 0xf7f8f4
const leftFill = 0xe9ebe5
const rightFill = 0xdde0d9
-const beltFill = 0xe6e8e2
-const hatch = 0xb4b9b1
+const roadFill = 0xe6e8e2
+const marking = 0xb4b9b1
+const leafFill = 0xe7ece0
+const waterFill = 0xdfe8e6
+const soilFill = 0xece8dc
+const ripe = 0xcdb46a
+const alarm = 0xc4523f
/** Outlines. */
const LINE = 1.5
-/** Everything inside an outline: seams, slats, windows, hatching. */
+/** Everything inside an outline: seams, slats, windows, markings. */
const DETAIL = 1
const STORY = 32
+const HUT = 20
+const HUT_ROOF = 14
const CHIMNEY = 24
-const PLATE = 23 * U
-const BELT = 4 * U
-const JOINT = 5 * U
-const JOINT_INNER = 2 * U
const DOOR = 5 * U
const DOOR_HEIGHT = 16
const AWNING = 6 * U
const AWNING_DEPTH = 3 * U
const CHIMNEY_HALF = 2 * U
+const CUPOLA_HALF = 3 * U
+const CUPOLA = 10
+const CUPOLA_CAP = 8
const CRATE = 3 * U
const CRATE_HEIGHT = 12
-const HATCH_GAP = 3 * U
-export const BELT_SPEED = 2.2
+/** Half a road's width. */
+const ROAD = 6 * U
+const HOUSE_DOOR = 2 * U
+const HOUSE_DOOR_HEIGHT = 9
+const HOUSE_ROOF = 8
+
+export type Emphasis = "normal" | "danger"
-/** The layers of the yard, back to front. */
+/** The layers of the town, back to front. */
export interface Stage {
readonly world: Container
+ readonly ground: Graphics
readonly plates: Container
- readonly belts: Container
+ readonly roads: Graphics
readonly preview: Container
readonly objects: Container
readonly labels: Container
@@ -68,7 +84,7 @@ const smooth = (t: number) => {
/**
* How far along each stage of putting a building up is, from `build` 0 → 1:
* the plate is marked out, a wire frame rises, the walls grow up inside it,
- * then the door, windows, and chimney are fitted.
+ * then the door, windows, and roof are fitted.
*/
export const buildStages = (build: number) => ({
plate: smooth(build / 0.12),
@@ -77,12 +93,16 @@ export const buildStages = (build: number) => ({
fit: smooth((build - 0.78) / 0.22)
})
-// ── Buildings ─────────────────────────────────────────────────────────────
+/** A stable number from 0 to 1 for a cell, so the land varies without being random each frame. */
+const hash = (x: number, y: number) => {
+ let h = (x * 374761393 + y * 668265263) >>> 0
+ h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296
+}
-/** Height of a kind's building at full size. */
-export const heightOf = (kind: Kind) => kind.stories * STORY
+// ── Shapes ────────────────────────────────────────────────────────────────
-/** A point of a building, around the centre of its footprint (u, v in cells, z in pixels). */
+/** A point around a footprint's centre (u, v in cells, z in pixels). */
const at = (u: number, v: number, z: number): Point => toScreen(u, v, z)
const quad = (g: Graphics, points: ReadonlyArray<Point>, fill: number, alpha = 1) =>
@@ -102,13 +122,16 @@ const square = (u: number, v: number, half: number, z = 0): Array<Point> => [
at(u - half, v + half, z)
]
-/** The plate a building stands on; while it is marked out, only its outline, growing. */
-export const drawPlate = (g: Graphics, alpha = 1, marked = 1, filled = true) => {
- g.poly(flat(square(0, 0, PLATE * (0.8 + 0.2 * marked))))
+/** A plate, `half` from its centre; while it is marked out, only its outline, growing. */
+const plate = (g: Graphics, half: number, alpha = 1, marked = 1, filled = true) => {
+ g.poly(flat(square(0, 0, half * (0.8 + 0.2 * marked))))
.fill({ color: plateFill, alpha: filled ? alpha : 0 })
.stroke({ color: ink, width: LINE, alpha: alpha * marked, join: "round" })
}
+/** Half a plate's width for a footprint `size` cells a side: a unit inside it. */
+const plateHalf = (size: number) => (size * 8 - 1) * U
+
/** The wire frame of a box, `h` pixels tall: every edge, the hidden ones too. */
const drawFrame = (g: Graphics, a: number, h: number) => {
const base = square(0, 0, a)
@@ -116,7 +139,67 @@ const drawFrame = (g: Graphics, a: number, h: number) => {
outline(g, square(0, 0, a, h), DETAIL)
}
-/** The centres of a roof's bays, back row first, in cells. */
+/** A point on one of the two walls facing the viewer: "right" faces +x (u = a), "left" faces +y (v = a). */
+type Side = "right" | "left"
+const onWall = (side: Side, a: number) => (along: number, out: number, z: number) =>
+ side === "right" ? at(a + out, along, z) : at(along, a + out, z)
+
+/** The two walls facing the viewer, `a` from the centre and `H` tall. */
+const walls = (g: Graphics, a: number, H: number) => {
+ quad(g, [at(-a, a, 0), at(a, a, 0), at(a, a, H), at(-a, a, H)], leftFill)
+ quad(g, [at(a, -a, 0), at(a, a, 0), at(a, a, H), at(a, -a, H)], rightFill)
+}
+
+/** A roof's two slopes: the one facing the viewer, and the one in shade. */
+interface RoofColors {
+ readonly face: number
+ readonly shade: number
+}
+const paleRoof: RoofColors = { face: roofFill, shade: rightFill }
+
+/**
+ * A gabled roof on walls `a` from the centre and `H` tall, rising `rise` px
+ * to a ridge along x (its gable end on the +x wall) or along y (on the +y
+ * wall). `chimney` puts a chimney on the slope in shade.
+ */
+const gable = (g: Graphics, a: number, H: number, rise: number, ridgeAlong: "x" | "y" = "x", colors: RoofColors = paleRoof, chimney = false) => {
+ const ridge = H + rise
+ const stack = () => {
+ if (!chimney || rise < 4) return
+ const c = U
+ const u = ridgeAlong === "x" ? -a / 2 : -a / 2
+ const v = ridgeAlong === "x" ? -a / 2 : a / 2
+ roofBox(g, u, v, c, H + Math.round(rise / 2), ridge + 4)
+ quad(g, square(u, v, c, ridge + 4), roofFill)
+ }
+ if (ridgeAlong === "x") {
+ quad(g, [at(-a, -a, H), at(a, -a, H), at(a, 0, ridge), at(-a, 0, ridge)], colors.shade)
+ stack()
+ quad(g, [at(a, -a, H), at(a, a, H), at(a, 0, ridge)], rightFill)
+ quad(g, [at(-a, a, H), at(a, a, H), at(a, 0, ridge), at(-a, 0, ridge)], colors.face)
+ } else {
+ quad(g, [at(-a, -a, H), at(-a, a, H), at(0, a, ridge), at(0, -a, ridge)], colors.shade)
+ stack()
+ quad(g, [at(-a, a, H), at(a, a, H), at(0, a, ridge)], leftFill)
+ quad(g, [at(a, -a, H), at(a, a, H), at(0, a, ridge), at(0, -a, ridge)], colors.face)
+ }
+}
+
+/** A small window, a unit either side of `along`, `z` to `z + 5` px up a wall. */
+const window_ = (g: Graphics, side: Side, a: number, along: number, z: number) => {
+ const p = onWall(side, a)
+ outline(g, [p(along - U, 0, z), p(along + U, 0, z), p(along + U, 0, z + 5), p(along - U, 0, z + 5)], DETAIL)
+}
+
+// ── Buildings ─────────────────────────────────────────────────────────────
+
+/** Height of a kind's walls at full size. */
+export const heightOf = (kind: Kind) => (kind.roof === "gable" ? HUT : kind.stories * STORY)
+/** Height of a kind's building at full size, roof and topper included. */
+export const topOf = (kind: Kind) =>
+ heightOf(kind) + (kind.roof === "gable" ? HUT_ROOF : kind.topper === "none" ? 0 : kind.topper === "sails" ? 20 : CHIMNEY)
+
+/** The centres of a flat roof's bays, back row first, in cells. */
const bays = (kind: Kind): Array<{ readonly u: number; readonly v: number; readonly index: number }> => {
const pitch = (2 * kind.half) / kind.bays
const out = []
@@ -128,18 +211,13 @@ const bays = (kind: Kind): Array<{ readonly u: number; readonly v: number; reado
return out
}
-/** The chimney stands in the back bay; a depot's flag in the right-hand one. */
-const chimneyBay = (kind: Kind) => bays(kind)[0]!
+/** The topper stands in the back bay; a flag in the right-hand one. */
+const backBay = (kind: Kind) => bays(kind)[0]!
const flagBay = (kind: Kind) => bays(kind)[kind.bays - 1]!
-/**
- * A loading door on a wall: `side` "right" is the wall facing down-right
- * (u = a), "left" the one facing down-left (v = a). Centred on the wall, as
- * the belt that meets it is.
- */
-const drawDoor = (g: Graphics, side: "right" | "left", a: number, H: number, fit: number, door: number, color: number) => {
- // On the right wall, points run along v; on the left wall, along u.
- const p = (along: number, out: number, z: number) => (side === "right" ? at(a + out, along, z) : at(along, a + out, z))
+/** A loading door on a wall, centred on it as the entrance is, with its awning. */
+const drawDoor = (g: Graphics, side: Side, a: number, H: number, fit: number, door: number, color: number) => {
+ const p = onWall(side, a)
const top = Math.round(Math.min(DOOR_HEIGHT, H - 8) * smooth((fit - 0.15) / 0.35))
if (top <= 0) return
const open = Math.round(top * door * 0.75)
@@ -148,7 +226,6 @@ const drawDoor = (g: Graphics, side: "right" | "left", a: number, H: number, fit
g.poly(flat([p(-DOOR, 0, open), p(DOOR, 0, open), p(DOOR, 0, top), p(-DOOR, 0, top)])).fill({ color: 0xeef0ea })
for (let z = top - 3; z > open; z -= 3) line(g, p(-DOOR, 0, z), p(DOOR, 0, z), DETAIL, 0x9aa29b)
outline(g, frame)
- // The awning above it, folding out as the door is fitted.
if (fit > 0.5) {
const out = AWNING_DEPTH * smooth((fit - 0.5) / 0.3)
quad(g, [p(-AWNING, 0, top + 4), p(AWNING, 0, top + 4), p(AWNING, out, top + 2), p(-AWNING, out, top + 2)], color)
@@ -156,18 +233,29 @@ const drawDoor = (g: Graphics, side: "right" | "left", a: number, H: number, fit
}
/** Vertical seams on a wall: framing the door when it has one, else one down the middle. */
-const drawSeams = (g: Graphics, side: "right" | "left", a: number, H: number, door: boolean) => {
- const p = (along: number, z: number) => (side === "right" ? at(a, along, z) : at(along, a, z))
+const drawSeams = (g: Graphics, side: Side, a: number, H: number, door: boolean) => {
+ const p = onWall(side, a)
const seams = door ? [-(a - 4 * U), a - 4 * U] : [0]
- for (const s of seams) line(g, p(s, 0), p(s, H), DETAIL, ink, 0.5)
+ for (const s of seams) line(g, p(s, 0, 0), p(s, 0, H), DETAIL, ink, 0.5)
+}
+
+/** A small box on the roof, `c` from its centre (u, v), from `base` up to `top`. */
+const roofBox = (g: Graphics, u: number, v: number, c: number, base: number, top: number) => {
+ quad(g, [at(u - c, v + c, base), at(u + c, v + c, base), at(u + c, v + c, top), at(u - c, v + c, top)], leftFill)
+ quad(g, [at(u + c, v - c, base), at(u + c, v + c, base), at(u + c, v + c, top), at(u + c, v - c, top)], rightFill)
+}
+
+/** Which walls facing the viewer have a door: where a road meets the building. */
+export interface Doors {
+ readonly right: boolean
+ readonly left: boolean
}
/**
* A building, `build` 0 → 1 of the way up (see `buildStages`); `door` 0
- * (shut) → 1 (open), `color` its awning's, `leftDoor` whether a belt meets
- * its left wall too (the right wall always has one).
+ * (shut) → 1 (open); `wave` drives flags and sails.
*/
-export const drawBuilding = (g: Graphics, kind: Kind, color: number, build: number, door: number, wave: number, leftDoor = false) => {
+export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: number, wave: number, doors: Doors, color = categoryColor[kind.category]) => {
const a = kind.half * U
const full = heightOf(kind)
const stage = buildStages(build)
@@ -176,41 +264,80 @@ export const drawBuilding = (g: Graphics, kind: Kind, color: number, build: numb
if (stage.walls <= 0) return
const H = Math.max(2, Math.round(full * stage.walls))
- // Walls: the one facing down-left, then the one facing down-right.
- quad(g, [at(-a, a, 0), at(a, a, 0), at(a, a, H), at(-a, a, H)], leftFill)
- quad(g, [at(a, -a, 0), at(a, a, 0), at(a, a, H), at(a, -a, H)], rightFill)
- drawSeams(g, "left", a, H, leftDoor)
- drawSeams(g, "right", a, H, true)
+ walls(g, a, H)
+ drawSeams(g, "left", a, H, doors.left)
+ drawSeams(g, "right", a, H, doors.right)
if (kind.stories === 2 && H > STORY) {
line(g, at(-a, a, STORY), at(a, a, STORY), DETAIL, ink, 0.7)
line(g, at(a, -a, STORY), at(a, a, STORY), DETAIL, ink, 0.7)
}
-
if (stage.fit > 0.15) {
- drawDoor(g, "right", a, H, stage.fit, door, color)
- if (leftDoor) drawDoor(g, "left", a, H, stage.fit, door, color)
+ if (doors.right) drawDoor(g, "right", a, H, stage.fit, door, color)
+ if (doors.left) drawDoor(g, "left", a, H, stage.fit, door, color)
+ }
+
+ if (kind.roof === "gable") {
+ if (stage.fit > 0.4) {
+ if (!doors.right) window_(g, "right", a, 0, 6)
+ if (!doors.left) window_(g, "left", a, 0, 6)
+ }
+ gable(g, a, H, Math.round(HUT_ROOF * stage.fit))
+ return
}
- // Roof (the top of the walls while they rise) and its windows, one by one.
+ // A flat roof (the top of the walls while they rise) and its windows, one by one.
quad(g, square(0, 0, a, H), roofFill)
+ const flag = kind.topper === "flag"
+ const usesBack = kind.topper !== "none" && kind.topper !== "flag" && kind.topper !== "sails"
if (stage.fit > 0.4) {
- const all = bays(kind).filter((bay) => bay.index !== 0 && !(kind.flag && bay.index === kind.bays - 1))
+ const all = bays(kind).filter((bay) => !(usesBack && bay.index === 0) && !(flag && bay.index === kind.bays - 1))
const shown = Math.ceil(all.length * smooth((stage.fit - 0.4) / 0.4))
for (const bay of all.slice(0, shown)) outline(g, square(bay.u, bay.v, (kind.window / 2) * U, H))
}
- // The chimney, rising last.
if (stage.fit > 0) {
- const { u, v } = chimneyBay(kind)
- const c = CHIMNEY_HALF
- const top = H + Math.round(CHIMNEY * stage.fit)
- quad(g, [at(u - c, v + c, H), at(u + c, v + c, H), at(u + c, v + c, top), at(u - c, v + c, top)], leftFill)
- quad(g, [at(u + c, v - c, H), at(u + c, v + c, H), at(u + c, v + c, top), at(u + c, v - c, top)], rightFill)
- quad(g, square(u, v, c, top), roofFill)
+ const { u, v } = backBay(kind)
+ if (kind.topper === "cupola") {
+ const c = CUPOLA_HALF
+ const top = H + Math.round(CUPOLA * stage.fit)
+ const apex = top + Math.round(CUPOLA_CAP * stage.fit)
+ roofBox(g, u, v, c, H, top)
+ outline(g, [at(u - U, v + c, top - 7), at(u + U, v + c, top - 7), at(u + U, v + c, top - 2), at(u - U, v + c, top - 2)], DETAIL)
+ outline(g, [at(u + c, v - U, top - 7), at(u + c, v + U, top - 7), at(u + c, v + U, top - 2), at(u + c, v - U, top - 2)], DETAIL)
+ quad(g, [at(u - c, v + c, top), at(u + c, v + c, top), at(u, v, apex)], leftFill)
+ quad(g, [at(u + c, v - c, top), at(u + c, v + c, top), at(u, v, apex)], rightFill)
+ } else if (kind.topper === "chimney") {
+ const top = H + Math.round(CHIMNEY * stage.fit)
+ roofBox(g, u, v, CHIMNEY_HALF, H, top)
+ quad(g, square(u, v, CHIMNEY_HALF, top), roofFill)
+ } else if (kind.topper === "crates") {
+ // Crates stacked on the roof's back bay.
+ if (stage.fit > 0.5) {
+ drawCrate(g, 0x8f9891, CRATE, CRATE_HEIGHT, H, u, v)
+ drawCrate(g, 0x8f9891, CRATE, CRATE_HEIGHT, H, u + 7 * U, v)
+ drawCrate(g, 0x8f9891, CRATE, CRATE_HEIGHT, H + CRATE_HEIGHT, u + 3 * U, v)
+ }
+ } else if (kind.topper === "sails" && stage.fit > 0.6) {
+ // Four sails on the wall facing +x, turning with `wave`.
+ const hub = at(a + U, 0, H - 8)
+ for (let i = 0; i < 4; i++) {
+ const turn = wave * 0.6 + (i * Math.PI) / 2
+ const d = { x: Math.cos(turn), y: Math.sin(turn) }
+ const n = { x: -d.y, y: d.x }
+ const tip = { x: hub.x + d.x * 22, y: hub.y + d.y * 22 }
+ line(g, hub, tip, LINE)
+ outline(g, [
+ { x: hub.x + d.x * 8, y: hub.y + d.y * 8 },
+ { x: tip.x, y: tip.y },
+ { x: tip.x + n.x * 4, y: tip.y + n.y * 4 },
+ { x: hub.x + d.x * 8 + n.x * 4, y: hub.y + d.y * 8 + n.y * 4 }
+ ], DETAIL)
+ }
+ g.circle(hub.x, hub.y, 2).fill({ color: roofFill }).stroke({ color: ink, width: DETAIL })
+ }
}
- // A depot flies a flag in its right-hand bay.
- if (kind.flag && stage.fit > 0.9) {
+ if (flag && stage.fit > 0.9) {
const { u, v } = flagBay(kind)
const base = at(u, v, H)
const tip = { x: base.x, y: base.y - 24 }
@@ -222,110 +349,112 @@ export const drawBuilding = (g: Graphics, kind: Kind, color: number, build: numb
/** Where a building's chimney puffs from, around its footprint's centre. */
export const chimneyTop = (kind: Kind): Point => {
- const { u, v } = chimneyBay(kind)
+ const { u, v } = backBay(kind)
return at(u, v, heightOf(kind) + CHIMNEY + 4)
}
-const statusColor: Readonly<Record<Status, number>> = {
- building: 0xb9beb5,
- idle: 0xb9beb5,
- working: 0x4f8a3e,
- starved: 0xd6ae2e,
- blocked: 0xc4523f
+/** A small red-edged marker with an exclamation mark: something keeps this building from working. */
+const drawMarker = (g: Graphics) => {
+ g.roundRect(-7.5, -7.5, 15, 15, 2).fill({ color: 0xf6f7f3 }).stroke({ color: alarm, width: 1 })
+ g.rect(-1, -4.5, 2, 6).fill({ color: alarm })
+ g.rect(-1, 2.5, 2, 2).fill({ color: alarm })
}
-const labelStyle = new TextStyle({
- fontFamily: "ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, monospace",
- fontSize: 13,
- fill: ink
-})
+/**
+ * A construction site on a plate `half` from its centre: a stake at each
+ * corner with a line strung between them, and crates of materials piling
+ * up at the front as `share` (0 → 1) of them arrives.
+ */
+export const drawSite = (g: Graphics, half: number, share: number) => {
+ const s = half - U
+ const tops = square(0, 0, s, 6)
+ outline(g, tops, DETAIL, ink, 0.45)
+ for (const [u, v] of [[-s, -s], [s, -s], [s, s], [-s, s]] as const) line(g, at(u, v, 0), at(u, v, 7), LINE)
+ const crates = Math.min(3, Math.ceil(share * 3))
+ const spots: ReadonlyArray<readonly [number, number, number]> = [[s - 3 * U, s - 3 * U, 0], [s - 3 * U, s - 8 * U, 0], [s - 3 * U, s - 5.5 * U, 5]]
+ for (let i = 0; i < crates; i++) {
+ const [u, v, z] = spots[i]!
+ drawCrate(g, 0x8f9891, 2 * U, 5, z, u, v)
+ }
+}
-interface Ring {
- age: number
+/** What a building view shows each frame. */
+export interface BuildingLook {
+ readonly working: boolean
+ /** Something keeps it from working: show the marker. */
+ readonly problem: boolean
+ /** 0 → 1 while it goes up. */
+ readonly build: number
+ /** Jobs finished, or walkers sent: each new one bounces the building. */
+ readonly beat: number
+ readonly doors: Doors
+ /** While a site: the share of its materials in, else `null`. */
+ readonly site: number | null
}
-/**
- * A factory as drawn: its plate on the floor, its building among the other
- * objects (sorted by depth), and its name tag above everything.
- */
-export class FactoryView extends Container {
+/** A building as drawn: its plate on the floor, its body among the other objects, and its problem marker above everything. */
+export class BuildingView extends Container {
private readonly kind: Kind
- private readonly color: number
private readonly plate = new Graphics()
- private readonly building = new Graphics()
+ private readonly body = new Graphics()
private readonly smoke = new Graphics()
- private readonly tag = new Container()
- private readonly tagBox = new Graphics()
- private readonly tagDot = new Graphics()
- private readonly tagText: Text
- private readonly rings: Array<Ring> = []
+ private readonly marker = new Graphics()
+ private readonly rings: Array<{ age: number }> = []
private puff = 0
private door = 0
private drawn = ""
private wave = 0
+ private pulse = 0
+ private beat = -1
- constructor(kindId: KindId, name: string, color: number, stage: Stage) {
+ constructor(kindId: KindId, stage: Stage) {
super()
- this.color = color
this.kind = kinds[kindId]
- this.addChild(this.building, this.smoke)
- this.tagText = new Text({ text: name, style: labelStyle, resolution: 3 })
- this.tagText.anchor.set(0, 0.5)
- this.tag.addChild(this.tagBox, this.tagDot, this.tagText)
+ this.addChild(this.body, this.smoke)
+ drawMarker(this.marker)
+ this.marker.visible = false
stage.plates.addChild(this.plate)
- stage.labels.addChild(this.tag)
- this.layoutTag()
- }
-
- /** The tag, in whole pixels: 8 px of padding, an 8 px status square, 6 px before the name. */
- private layoutTag() {
- const pad = 8
- const dot = 8
- const gap = 6
- const width = 2 * Math.ceil((pad + dot + gap + this.tagText.width + pad) / 2)
- const height = 22
- this.tagBox.clear()
- .roundRect(-width / 2 + 0.5, -height / 2 + 0.5, width - 1, height - 1, 3)
- .fill({ color: 0xf6f7f3 })
- .stroke({ color: 0xbfc5bc, width: 1 })
- this.tagDot.position.set(-width / 2 + pad + dot / 2, 0)
- this.tagText.position.set(-width / 2 + pad + dot + gap, 0)
+ stage.labels.addChild(this.marker)
}
/** Puts it on the grid by its footprint's top cell. */
place(x: number, y: number) {
- const centre = toScreen(x + FOOTPRINT / 2, y + FOOTPRINT / 2)
+ const s = this.kind.size
+ const centre = toScreen(x + s / 2, y + s / 2)
this.position.set(centre.x, centre.y)
this.plate.position.set(centre.x, centre.y)
- this.zIndex = x + y + FOOTPRINT
- this.tag.position.set(centre.x, centre.y - heightOf(this.kind) - CHIMNEY - 24)
+ this.zIndex = x + y + s
+ this.marker.position.set(centre.x, centre.y - topOf(this.kind) - 14)
}
- /** Follows the factory's work: rising, doors, smoke, bounce, and status. */
- update(work: WorkValue, dt: number, emphasis: "normal" | "dim" | "focus" | "danger", leftDoor: boolean) {
- const build = Math.min(1, work.built)
- const opening = work.status === "working" || work.pulse > 0.2 ? 1 : 0
+ update(look: BuildingLook, dt: number, emphasis: Emphasis) {
+ if (this.beat >= 0 && look.beat > this.beat) this.pulse = 1
+ this.beat = look.beat
+ this.pulse = Math.max(0, this.pulse - dt * 3)
+ const opening = look.working || this.pulse > 0.2 ? 1 : 0
this.door += (opening - this.door) * Math.min(1, dt * 6)
- this.wave += dt * (this.kind.flag && work.status === "working" ? 9 : 3)
+ const moving = this.kind.topper === "flag" || (this.kind.topper === "sails" && look.working)
+ if (moving) this.wave += dt * (look.working ? 6 : 3)
// Redrawn only when something it shows moved by a whole pixel's worth.
- const key = `${build.toFixed(3)}|${Math.round(this.door * 12)}|${leftDoor}|${this.kind.flag ? Math.round(Math.sin(this.wave) * 2) : ""}`
+ const motion = this.kind.topper === "flag" ? Math.round(Math.sin(this.wave) * 2) : this.kind.topper === "sails" ? Math.round(this.wave * 20) : 0
+ const key = `${look.build.toFixed(3)}|${Math.round(this.door * 12)}|${look.doors.right}|${look.doors.left}|${motion}|${look.site?.toFixed(2)}`
if (key !== this.drawn) {
this.drawn = key
- this.building.clear()
- drawBuilding(this.building, this.kind, this.color, build, this.door, this.wave, leftDoor)
- const stage = buildStages(build)
+ this.body.clear()
+ if (look.site !== null) drawSite(this.body, plateHalf(this.kind.size), look.site)
+ drawBuilding(this.body, this.kind, look.build, this.door, this.wave, look.doors)
+ const stage = buildStages(look.build)
this.plate.clear()
- drawPlate(this.plate, 1, stage.plate, stage.walls > 0)
+ plate(this.plate, plateHalf(this.kind.size), 1, stage.plate, stage.walls > 0)
}
// A small bounce when a job finishes; at rest it is exactly its drawn size.
- const p = work.pulse
- this.building.scale.set(1 + p * 0.04, 1 - p * 0.06)
+ this.body.scale.set(1 + this.pulse * 0.04, 1 - this.pulse * 0.06)
- // Smoke rings, while working.
+ // Smoke rings from a chimney, while working.
this.puff -= dt
- if (work.status === "working" && this.puff <= 0) {
+ if (look.working && this.kind.topper === "chimney" && this.puff <= 0) {
this.rings.push({ age: 0 })
this.puff = 0.7
}
@@ -339,145 +468,411 @@ export class FactoryView extends Container {
continue
}
const t = ring.age
- this.smoke.circle(top.x + Math.sin(t * 5) * 1.5, top.y - t * 34, 4 + t * 7)
- .stroke({ color: ink, width: DETAIL, alpha: (1 - t) * 0.55 })
+ this.smoke.circle(top.x + Math.sin(t * 5) * 1.5, top.y - t * 34, 4 + t * 7).stroke({ color: ink, width: DETAIL, alpha: (1 - t) * 0.55 })
}
- // The tag's status square: filled while it has something to say, hollow when idle.
- const blink = work.status === "blocked" ? 0.55 + 0.45 * Math.sin(this.wave * 3) : 1
- this.tagDot.clear()
- if (work.status === "idle" || work.status === "building") this.tagDot.rect(-3.5, -3.5, 7, 7).stroke({ color: 0x9aa09a, width: 1 })
- else this.tagDot.rect(-4, -4, 8, 8).fill({ color: statusColor[work.status], alpha: blink })
-
- const alpha = emphasis === "dim" ? 0.28 : 1
- this.alpha = alpha
- this.plate.alpha = alpha
- this.tag.alpha = (emphasis === "dim" ? 0.4 : 1) * buildStages(build).walls
- this.building.tint = emphasis === "danger" ? 0xf3b5aa : 0xffffff
- this.tagBox.tint = emphasis === "focus" ? 0xdfe6dc : 0xffffff
+ this.marker.visible = look.problem && look.build >= 1
+ this.body.tint = emphasis === "danger" ? 0xf3b5aa : 0xffffff
}
override destroy(options?: Parameters<Container["destroy"]>[0]) {
this.plate.destroy()
- this.tag.destroy({ children: true })
+ this.marker.destroy()
super.destroy(options)
}
}
-// ── Belts ─────────────────────────────────────────────────────────────────
+// ── Homes ─────────────────────────────────────────────────────────────────
-const along = (a: Point, b: Point) => {
- const length = Math.hypot(b.x - a.x, b.y - a.y)
- const d = length === 0 ? { x: 1, y: 0 } : { x: (b.x - a.x) / length, y: (b.y - a.y) / length }
- return { length, d, p: { x: -d.y, y: d.x } }
-}
+/** A home's full height, roof included. */
+export const homeHeight = (tier: Tier) => home.tiers[tier].height + HOUSE_ROOF + (tier === 2 ? 2 : 0)
+
+/** Roof colours homes are built with: muted terracotta, slate, thatch, and moss. */
+const homeRoofs: ReadonlyArray<RoofColors> = [
+ { face: 0xe6c3b2, shade: 0xd3ab98 },
+ { face: 0xc9d2da, shade: 0xb3bec8 },
+ { face: 0xe4dab8, shade: 0xd1c59f },
+ { face: 0xd0d9c5, shade: 0xbac5ae }
+]
-/** A straight run of belt from `a` to `b`, `half` either side of the centre line. */
-const strip = (a: Point, b: Point, half: number): [Point, Point, Point, Point] => {
- const { p } = along(a, b)
- return [
- toScreen(a.x + p.x * half, a.y + p.y * half),
- toScreen(b.x + p.x * half, b.y + p.y * half),
- toScreen(b.x - p.x * half, b.y - p.y * half),
- toScreen(a.x - p.x * half, a.y - p.y * half)
- ]
+/** How a home is built, from a number 0 → 1 fixed for its cell: roof colour, which way its ridge runs, a chimney. */
+export interface HomeVariant {
+ readonly roof: RoofColors
+ readonly ridge: "x" | "y"
+ readonly chimney: boolean
}
+export const homeVariant = (n: number): HomeVariant => ({
+ roof: homeRoofs[Math.floor(n * homeRoofs.length) % homeRoofs.length]!,
+ ridge: Math.floor(n * 97) % 2 === 0 ? "x" : "y",
+ chimney: Math.floor(n * 31) % 3 !== 0
+})
+const plainHome: HomeVariant = { roof: paleRoof, ridge: "x", chimney: false }
-/** A square on the floor in grid coordinates. */
-const tile = (c: Point, half: number): Array<Point> => [
- toScreen(c.x - half, c.y - half),
- toScreen(c.x + half, c.y - half),
- toScreen(c.x + half, c.y + half),
- toScreen(c.x - half, c.y + half)
-]
+/**
+ * A home, `build` 0 → 1 of the way up: walls, a door on each wall a road
+ * meets with an awning in its roof's colour, windows on the rest, and a
+ * gabled roof. A citizens' home is wider, with a second story and a window
+ * either side on every floor.
+ */
+export const drawHouse = (g: Graphics, tier: Tier, build: number, doors: Doors, variant: HomeVariant = plainHome) => {
+ const a = (tier === 2 ? home.half + 1 : home.half) * U
+ const full = home.tiers[tier].height
+ const stage = buildStages(build)
+ if (stage.frame <= 0) return
+ if (stage.walls < 1) drawFrame(g, a, Math.round(full * stage.frame))
+ if (stage.walls <= 0) return
+ const H = Math.max(2, Math.round(full * stage.walls))
-/** A belt's surface. */
-export const drawBeltBase = (g: Graphics, points: ReadonlyArray<Point>, alpha = 1) => {
- for (let i = 1; i < points.length; i++) g.poly(flat(strip(points[i - 1]!, points[i]!, BELT))).fill({ color: beltFill, alpha })
-}
-
-/** A belt's rails, square ends, and square joints at the turns. */
-export const drawBeltRails = (g: Graphics, points: ReadonlyArray<Point>, alpha = 1, color = ink) => {
- for (let i = 1; i < points.length; i++) {
- const [p0, p1, p2, p3] = strip(points[i - 1]!, points[i]!, BELT)
- line(g, p0, p1, LINE, color, alpha)
- line(g, p3, p2, LINE, color, alpha)
- }
- const first = strip(points[0]!, points[1]!, BELT)
- line(g, first[0], first[3], LINE, color, alpha)
- const last = strip(points[points.length - 2]!, points[points.length - 1]!, BELT)
- line(g, last[1], last[2], LINE, color, alpha)
- for (let i = 1; i < points.length - 1; i++) {
- const c = points[i]!
- g.poly(flat(tile(c, JOINT))).fill({ color: beltFill, alpha }).stroke({ color, width: LINE, alpha, join: "round" })
- g.poly(flat(tile(c, JOINT_INNER))).stroke({ color, width: DETAIL, alpha: alpha * 0.8, join: "round" })
- }
-}
-
-/** The hatching across a belt, rail to rail, scrolled by `offset` (cells) towards its end. */
-export const drawBeltHatch = (g: Graphics, points: ReadonlyArray<Point>, offset: number, alpha = 1) => {
- let start = 0
- for (let i = 1; i < points.length; i++) {
- const a = points[i - 1]!
- const { length, d, p } = along(a, points[i]!)
- let s = (((offset - start) % HATCH_GAP) + HATCH_GAP) % HATCH_GAP
- for (; s < length; s += HATCH_GAP) {
- const c = { x: a.x + d.x * s, y: a.y + d.y * s }
- const l = toScreen(c.x + p.x * BELT, c.y + p.y * BELT)
- const r = toScreen(c.x - p.x * BELT, c.y - p.y * BELT)
- g.moveTo(l.x, l.y).lineTo(r.x, r.y)
+ walls(g, a, H)
+ const floors = tier === 2 ? [0, 12] : [0]
+ if (tier === 2 && H > 13) {
+ line(g, at(-a, a, 13), at(a, a, 13), DETAIL, ink, 0.7)
+ line(g, at(a, -a, 13), at(a, a, 13), DETAIL, ink, 0.7)
+ }
+ if (stage.fit > 0.15) {
+ for (const side of ["right", "left"] as const) {
+ const p = onWall(side, a)
+ floors.forEach((floor, index) => {
+ const door = index === 0 && doors[side]
+ if (door) {
+ const top = Math.round(HOUSE_DOOR_HEIGHT * smooth((stage.fit - 0.15) / 0.35))
+ if (top <= 0) return
+ quad(g, [p(-HOUSE_DOOR, 0, 0), p(HOUSE_DOOR, 0, 0), p(HOUSE_DOOR, 0, top), p(-HOUSE_DOOR, 0, top)], 0x8f9891)
+ if (stage.fit > 0.5) {
+ const out = 2 * U * smooth((stage.fit - 0.5) / 0.3)
+ quad(g, [p(-3 * U, 0, top + 3), p(3 * U, 0, top + 3), p(3 * U, out, top + 1), p(-3 * U, out, top + 1)], variant.roof.shade)
+ }
+ }
+ if (floor + 10 > H) return
+ if (tier === 2) {
+ for (const along of [-3 * U, 3 * U]) if (!(door && Math.abs(along) < HOUSE_DOOR + 2 * U)) window_(g, side, a, along, floor + 5)
+ } else if (!door) window_(g, side, a, 0, floor + 5)
+ })
}
- start += length
}
- g.stroke({ color: hatch, width: DETAIL, alpha })
+ gable(g, a, H, Math.round((HOUSE_ROOF + (tier === 2 ? 2 : 0)) * stage.fit), variant.ridge, variant.roof, variant.chimney || tier === 2)
+}
+
+/** What a home view shows each frame. */
+export interface HouseLook {
+ readonly tier: Tier
+ readonly build: number
+ readonly doors: Doors
+ /** While a site: the share of its materials in, else `null`. */
+ readonly site: number | null
}
-export class BeltView extends Container {
- private readonly base = new Graphics()
- private readonly hatching = new Graphics()
- private readonly rails = new Graphics()
- private readonly points: ReadonlyArray<Point>
+export class HouseView extends Container {
+ private readonly plate = new Graphics()
+ private readonly body = new Graphics()
+ private drawn = ""
+ private variant: HomeVariant = plainHome
- constructor(points: ReadonlyArray<Point>) {
+ constructor(stage: Stage) {
super()
- this.points = points
- drawBeltBase(this.base, points)
- drawBeltRails(this.rails, points)
- this.addChild(this.base, this.hatching, this.rails)
+ this.addChild(this.body)
+ stage.plates.addChild(this.plate)
+ }
+
+ place(x: number, y: number) {
+ const centre = toScreen(x + 0.5, y + 0.5)
+ this.position.set(centre.x, centre.y)
+ this.plate.position.set(centre.x, centre.y)
+ this.zIndex = x + y + 1
+ this.variant = homeVariant(hash(x, y))
+ this.drawn = ""
+ }
+
+ update(look: HouseLook, emphasis: Emphasis) {
+ const key = `${look.tier}|${look.build.toFixed(3)}|${look.doors.right}|${look.doors.left}|${look.site?.toFixed(2)}`
+ if (key !== this.drawn) {
+ this.drawn = key
+ this.body.clear()
+ if (look.site !== null) drawSite(this.body, plateHalf(1), look.site)
+ drawHouse(this.body, look.tier, look.build, look.doors, this.variant)
+ const stage = buildStages(look.build)
+ this.plate.clear()
+ plate(this.plate, plateHalf(1), 1, stage.plate, stage.walls > 0)
+ }
+ this.body.tint = emphasis === "danger" ? 0xf3b5aa : 0xffffff
}
- update(time: number, emphasis: "normal" | "dim" | "focus" | "danger") {
- this.hatching.clear()
- drawBeltHatch(this.hatching, this.points, time * BELT_SPEED)
- this.alpha = emphasis === "dim" ? 0.25 : 1
+ override destroy(options?: Parameters<Container["destroy"]>[0]) {
+ this.plate.destroy()
+ super.destroy(options)
+ }
+}
+
+// ── The land ──────────────────────────────────────────────────────────────
+
+/**
+ * A tree, `grown` 0 → 1: a trunk and a crown, a pointed fir or a round
+ * broadleaf depending on its cell. It grows in three whole-pixel steps.
+ */
+export const drawTree = (g: Graphics, x: number, y: number, grown: number) => {
+ const h = hash(x, y)
+ const size = grown >= 1 ? 1 : grown >= 0.5 ? 0.75 : 0.5
+ const trunk = Math.round(6 * size)
+ const ox = Math.round((h - 0.5) * 8)
+ line(g, { x: ox, y: 0 }, { x: ox, y: -trunk }, LINE)
+ if (h < 0.55) {
+ const w = Math.round(7 * size)
+ const tall = Math.round(22 * size)
+ g.poly([ox - w, -trunk, ox, -trunk - tall, ox + w, -trunk]).fill({ color: leafFill }).stroke({ color: ink, width: LINE, join: "round" })
+ line(g, { x: ox - Math.round(w * 0.6), y: -trunk - Math.round(tall * 0.4) }, { x: ox + Math.round(w * 0.6), y: -trunk - Math.round(tall * 0.4) }, DETAIL, ink, 0.5)
+ } else {
+ const r = Math.round(7 * size)
+ g.circle(ox, -trunk - r, r).fill({ color: leafFill }).stroke({ color: ink, width: LINE })
+ line(g, { x: ox - Math.round(r * 0.4), y: -trunk - r + 1 }, { x: ox + Math.round(r * 0.2), y: -trunk - r - Math.round(r * 0.5) }, DETAIL, ink, 0.4)
+ }
+}
+
+export class TreeView extends Graphics {
+ private stage = -1
+ private x0 = 0
+ private y0 = 0
+
+ place(x: number, y: number) {
+ this.x0 = x
+ this.y0 = y
+ const s = toScreen(x + 0.5, y + 0.5)
+ this.position.set(s.x, s.y)
+ this.zIndex = x + y + 1
+ }
+
+ update(growth: number, emphasis: Emphasis) {
+ const grown = growth / GROWN.tree
+ const stage = grown >= 1 ? 2 : grown >= 0.5 ? 1 : 0
+ if (stage !== this.stage) {
+ this.stage = stage
+ this.clear()
+ drawTree(this, this.x0, this.y0, grown)
+ }
this.tint = emphasis === "danger" ? 0xf3b5aa : 0xffffff
}
}
-// ── Crates ────────────────────────────────────────────────────────────────
+/** A rock: a low faceted boulder, smaller as it is quarried; an ore rock has dark flecks. */
+export const drawRock = (g: Graphics, x: number, y: number, ore: boolean, left: number) => {
+ const h = hash(x, y)
+ const s = left > ROCK_AMOUNT / 2 ? 5 * U : 4 * U
+ const tall = left > ROCK_AMOUNT / 2 ? 10 : 7
+ const u = (h - 0.5) * 4 * U
+ quad(g, [at(u - s, s, 0), at(u + s, s, 0), at(u + s, s * 0.4, tall), at(u - s * 0.6, s * 0.4, tall)], leftFill)
+ quad(g, [at(u + s, -s, 0), at(u + s, s, 0), at(u + s, s * 0.4, tall), at(u + s * 0.4, -s * 0.6, tall)], rightFill)
+ quad(g, [at(u - s * 0.6, -s * 0.6, tall), at(u + s * 0.4, -s * 0.6, tall), at(u + s, s * 0.4, tall), at(u - s * 0.6, s * 0.4, tall)], roofFill)
+ if (ore) {
+ for (const [du, dv, z] of [[-0.3, 1, 3], [0.2, 1, 6], [1, 0.1, 4]] as const) {
+ const p = du === 1 ? at(u + s, dv * s, z) : at(u + du * s, s, z)
+ g.rect(Math.round(p.x) - 1, Math.round(p.y) - 1, 2, 2).fill({ color: ink })
+ }
+ }
+}
+
+export class RockView extends Graphics {
+ private drawn = ""
+ private x0 = 0
+ private y0 = 0
+
+ place(x: number, y: number) {
+ this.x0 = x
+ this.y0 = y
+ const s = toScreen(x + 0.5, y + 0.5)
+ this.position.set(s.x, s.y)
+ this.zIndex = x + y + 1
+ }
+
+ update(ore: boolean, amount: number) {
+ const key = `${ore}|${amount > ROCK_AMOUNT / 2}`
+ if (key !== this.drawn) {
+ this.drawn = key
+ this.clear()
+ drawRock(this, this.x0, this.y0, ore, amount)
+ }
+ }
+}
+
+/** A field: soil with three furrows, sprouting as it grows and golden when ripe. */
+export const drawField = (g: Graphics, grown: number) => {
+ const s = 7 * U
+ g.poly(flat(square(0, 0, s))).fill({ color: soilFill }).stroke({ color: ink, width: DETAIL, alpha: 0.6 })
+ const stage = grown >= 1 ? 3 : Math.floor(grown * 3)
+ for (const v of [-4 * U, 0, 4 * U]) {
+ line(g, at(-s + U, v, 0), at(s - U, v, 0), DETAIL, ink, 0.35)
+ if (stage === 0) continue
+ for (let u = -s + 2 * U; u <= s - 2 * U; u += 2 * U) {
+ const p = at(u, v, 0)
+ const h = stage + 1
+ g.moveTo(p.x, p.y).lineTo(p.x, p.y - h)
+ }
+ g.stroke({ color: stage === 3 ? ripe : ink, width: DETAIL, alpha: stage === 3 ? 1 : 0.6 })
+ }
+}
+
+export class FieldView extends Graphics {
+ private stage = -1
+
+ place(x: number, y: number) {
+ const s = toScreen(x + 0.5, y + 0.5)
+ this.position.set(s.x, s.y)
+ }
+
+ update(growth: number) {
+ const grown = growth / GROWN.field
+ const stage = grown >= 1 ? 3 : Math.floor(grown * 3)
+ if (stage !== this.stage) {
+ this.stage = stage
+ this.clear()
+ drawField(this, grown)
+ }
+ }
+}
+
+/** Water on a set of cells (by `key`): pale fill, an ink shoreline where it meets land, and a few ripples. */
+export const drawWater = (g: Graphics, cells: ReadonlySet<number>) => {
+ for (const k of cells) {
+ const c = cellOf(k)
+ g.poly(flat([toScreen(c.x, c.y), toScreen(c.x + 1, c.y), toScreen(c.x + 1, c.y + 1), toScreen(c.x, c.y + 1)])).fill({ color: waterFill })
+ }
+ for (const k of cells) {
+ const c = cellOf(k)
+ if (hash(c.x, c.y) < 0.3) {
+ const a = toScreen(c.x + 0.3, c.y + 0.5)
+ const b = toScreen(c.x + 0.6, c.y + 0.5)
+ g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ }
+ }
+ g.stroke({ color: 0x9fb3b0, width: DETAIL })
+ for (const k of cells) {
+ const c = cellOf(k)
+ const edges: ReadonlyArray<readonly [Point, Point, Point]> = [
+ [DIRS[0]!, { x: c.x + 1, y: c.y }, { x: c.x + 1, y: c.y + 1 }],
+ [DIRS[1]!, { x: c.x, y: c.y + 1 }, { x: c.x + 1, y: c.y + 1 }],
+ [DIRS[2]!, { x: c.x, y: c.y }, { x: c.x, y: c.y + 1 }],
+ [DIRS[3]!, { x: c.x, y: c.y }, { x: c.x + 1, y: c.y }]
+ ]
+ for (const [d, p, q] of edges) {
+ const n = { x: c.x + d.x, y: c.y + d.y }
+ const inside = n.x >= 0 && n.y >= 0 && n.x < GRID && n.y < GRID
+ if (inside && !cells.has(key(n.x, n.y))) {
+ const a = toScreen(p.x, p.y)
+ const b = toScreen(q.x, q.y)
+ g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ }
+ }
+ }
+ g.stroke({ color: ink, width: LINE, alpha: 0.7, cap: "square" })
+}
+
+// ── Roads ─────────────────────────────────────────────────────────────────
+
+/**
+ * Roads on a set of cells (by `key`): each cell is a square of paving at its
+ * centre with an arm to every neighbour that is road too, kerbs along the
+ * outside, and a dashed line down the middle of each arm. Arms meet their
+ * neighbours' at the cell edge, so a run of road reads as one strip with
+ * square joints.
+ */
+export const drawRoads = (g: Graphics, cells: ReadonlySet<number>, alpha = 1, kerb = ink) => {
+ const w = ROAD
+ const edge = 8 * U
+ const kerbs: Array<readonly [Point, Point]> = []
+ const dashes: Array<readonly [Point, Point]> = []
+ for (const k of cells) {
+ const c = cellOf(k)
+ const cx = c.x + 0.5
+ const cy = c.y + 0.5
+ const p = (u: number, v: number) => toScreen(cx + u, cy + v)
+ g.poly(flat([p(-w, -w), p(w, -w), p(w, w), p(-w, w)])).fill({ color: roadFill, alpha })
+ for (const d of DIRS) {
+ const n = { x: -d.y, y: d.x }
+ const q = (along: number, across: number) => p(d.x * along + n.x * across, d.y * along + n.y * across)
+ if (cells.has(key(c.x + d.x, c.y + d.y))) {
+ g.poly(flat([q(w, -w), q(edge, -w), q(edge, w), q(w, w)])).fill({ color: roadFill, alpha })
+ kerbs.push([q(w, -w), q(edge, -w)], [q(w, w), q(edge, w)])
+ dashes.push([q(U, 0), q(3 * U, 0)], [q(5 * U, 0), q(7 * U, 0)])
+ } else kerbs.push([q(w, -w), q(w, w)])
+ }
+ }
+ for (const [a, b] of dashes) g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ g.stroke({ color: marking, width: DETAIL, alpha })
+ for (const [a, b] of kerbs) g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ g.stroke({ color: kerb, width: LINE, alpha, cap: "square" })
+}
+
+// ── Crates and walkers ────────────────────────────────────────────────────
-/** A crate, 6 units square and 12 px tall, sitting on its belt. */
-export const drawCrate = (g: Graphics, label: number) => {
- const s = CRATE
- const h = CRATE_HEIGHT
+/** A crate, `s` from its centre at (u, v) and `h` px tall, standing `z` px up, with a label in its good's colour. */
+export const drawCrate = (g: Graphics, label: number, s = CRATE, h = CRATE_HEIGHT, z = 0, u = 0, v = 0) => {
const edge = 0x7d6140
const face = (points: ReadonlyArray<Point>, fill: number) =>
g.poly(flat(points)).fill({ color: fill }).stroke({ color: edge, width: DETAIL, join: "round" })
- face([at(-s, s, 0), at(s, s, 0), at(s, s, h), at(-s, s, h)], 0xe9c48a)
- face([at(s, -s, 0), at(s, s, 0), at(s, s, h), at(s, -s, h)], 0xd5a86c)
- face(square(0, 0, s, h), 0xf4dcab)
- // Tape across the lid, a unit wide, and the label of the factory that made it.
- g.poly(flat([at(-s, -0.5 * U, h), at(s, -0.5 * U, h), at(s, 0.5 * U, h), at(-s, 0.5 * U, h)])).fill({ color: 0xc79a5b })
- g.poly(flat([at(-2 * U, s, 3), at(U, s, 3), at(U, s, 8), at(-2 * U, s, 8)])).fill({ color: label })
+ face([at(u - s, v + s, z), at(u + s, v + s, z), at(u + s, v + s, z + h), at(u - s, v + s, z + h)], 0xe9c48a)
+ face([at(u + s, v - s, z), at(u + s, v + s, z), at(u + s, v + s, z + h), at(u + s, v - s, z + h)], 0xd5a86c)
+ face(square(u, v, s, z + h), 0xf4dcab)
+ g.poly(flat([at(u - s, v - 0.5 * U, z + h), at(u + s, v - 0.5 * U, z + h), at(u + s, v + 0.5 * U, z + h), at(u - s, v + 0.5 * U, z + h)])).fill({ color: 0xc79a5b })
+ const lh = Math.max(2, Math.round(h * 0.4))
+ const lz = z + Math.round((h - lh) / 2)
+ g.poly(flat([at(u - s + U, v + s, lz), at(u + s - U, v + s, lz), at(u + s - U, v + s, lz + lh), at(u - s + U, v + s, lz + lh)])).fill({ color: label })
+}
+
+/**
+ * A walker: a small pale figure on two stepping legs, facing `dir` (a grid
+ * step). A service walker's head is in its building's colour, and a
+ * provisions walker carries a basket at its side. A carrier's head is pale;
+ * it pushes a handcart ahead of it, with a crate labelled with its good on
+ * the way out.
+ */
+export const drawWalker = (g: Graphics, role: "carrier" | "walker", color: number, cargo: boolean, dir: Point, phase: number) => {
+ const d = dir.x === 0 && dir.y === 0 ? { x: 1, y: 0 } : dir
+ const ahead = { u: d.x * 5 * U, v: d.y * 5 * U }
+ const front = toScreen(ahead.u, ahead.v)
+ const figure = () => {
+ const swing = phase === 0 ? 1 : -1
+ line(g, { x: -1, y: -5 }, { x: -1 + swing, y: 0 }, DETAIL)
+ line(g, { x: 1, y: -5 }, { x: 1 - swing, y: 0 }, DETAIL)
+ g.roundRect(-2.5, -11, 5, 7, 2).fill({ color: plateFill }).stroke({ color: ink, width: DETAIL })
+ g.circle(0, -13.5, 2.2).fill({ color: role === "walker" ? color : plateFill }).stroke({ color: ink, width: DETAIL })
+ if (role === "walker" && cargo) {
+ const side = front.x >= 0 ? -1 : 1
+ g.rect(side * 4 - 1.5, -8, 3, 3).fill({ color: 0xe9c48a }).stroke({ color: 0x7d6140, width: DETAIL })
+ }
+ }
+ const cart = () => {
+ // Handles from the walker's hands to the cart, a wheel, and the bed or the crate on it.
+ line(g, { x: front.x * 0.3, y: front.y * 0.3 - 7 }, { x: front.x * 0.7, y: front.y * 0.7 - 4 }, DETAIL)
+ g.circle(front.x, front.y - 1, 1.5).fill({ color: ink })
+ if (cargo) drawCrate(g, color, 2 * U, 5, 2, ahead.u, ahead.v)
+ else quad(g, square(ahead.u, ahead.v, 2 * U, 2), roofFill)
+ }
+ if (role === "carrier" && front.y < 0) {
+ cart()
+ figure()
+ } else {
+ figure()
+ if (role === "carrier") cart()
+ }
}
-export class CrateView extends Graphics {
- constructor(label: number) {
+export class WalkerView extends Graphics {
+ private readonly role: "carrier" | "walker"
+ private readonly color: number
+ private drawn = ""
+
+ constructor(role: "carrier" | "walker", color: number) {
super()
- drawCrate(this, label)
+ this.role = role
+ this.color = color
}
- place(x: number, y: number) {
+ /** Puts it on the floor at grid point (x, y), facing `dir`, redrawing when its stride, heading, or load changes. */
+ update(x: number, y: number, dir: Point, phase: number, cargo: boolean) {
+ const key = `${dir.x},${dir.y}|${phase}|${cargo}`
+ if (key !== this.drawn) {
+ this.drawn = key
+ this.clear()
+ drawWalker(this, this.role, this.color, cargo, dir, phase)
+ }
const s = toScreen(x, y)
this.position.set(s.x, s.y)
this.zIndex = x + y
@@ -486,7 +881,7 @@ export class CrateView extends Graphics {
// ── The floor ─────────────────────────────────────────────────────────────
-/** The grid: a faint line between every two cells, and the yard's edge. */
+/** The grid: a faint line between every two cells, and the map's edge. */
export const drawFloor = (g: Graphics) => {
for (let i = 1; i < GRID; i++) {
const a = toScreen(i, 0)
@@ -495,25 +890,23 @@ export const drawFloor = (g: Graphics) => {
const d = toScreen(GRID, i)
g.moveTo(a.x, a.y).lineTo(b.x, b.y).moveTo(c.x, c.y).lineTo(d.x, d.y)
}
- g.stroke({ color: 0xd9ddd3, width: DETAIL })
+ g.stroke({ color: 0xe0e3db, width: DETAIL })
outline(g, [toScreen(0, 0), toScreen(GRID, 0), toScreen(GRID, GRID), toScreen(0, GRID)], LINE, 0xb9bfb4)
}
/**
- * A plot on the floor: under the pointer (`hover`), picked for building
- * (`picked`, with corner ticks that breathe with `time`), or with no room
- * (`blocked`).
+ * An outline on the floor, `n` cells a side: under the pointer (`hover`),
+ * picked (`picked`, with corner ticks that breathe with `time`), with no
+ * room (`blocked`), or the reach of a building's work (`reach`).
*/
-export const drawPlot = (g: Graphics, x: number, y: number, look: "hover" | "picked" | "blocked", time = 0) => {
- const n = FOOTPRINT
+export const drawPlot = (g: Graphics, x: number, y: number, n: number, look: "hover" | "picked" | "blocked" | "reach", time = 0) => {
const corners = [toScreen(x, y), toScreen(x + n, y), toScreen(x + n, y + n), toScreen(x, y + n)]
- if (look === "hover") {
- g.poly(flat(corners)).fill({ color: ink, alpha: 0.04 }).stroke({ color: ink, width: DETAIL, alpha: 0.35 })
+ if (look === "hover" || look === "reach") {
+ g.poly(flat(corners)).fill({ color: ink, alpha: look === "reach" ? 0.03 : 0.04 }).stroke({ color: ink, width: DETAIL, alpha: look === "reach" ? 0.45 : 0.35 })
return
}
- const color = look === "blocked" ? 0xc4523f : ink
+ const color = look === "blocked" ? alarm : ink
g.poly(flat(corners)).fill({ color, alpha: 0.07 }).stroke({ color, width: LINE, alpha: 0.85 })
- // Corner ticks a unit outside the plot, 4 units long (breathing by a unit).
const reach = (4 + Math.sin(time * 4)) * U
const ticks: ReadonlyArray<readonly [number, number, number, number]> = [[x, y, 1, 1], [x + n, y, -1, 1], [x + n, y + n, -1, -1], [x, y + n, 1, -1]]
for (const [cx, cy, sx, sy] of ticks) {
@@ -526,3 +919,13 @@ export const drawPlot = (g: Graphics, x: number, y: number, look: "hover" | "pic
}
g.stroke({ color, width: LINE, alpha: 0.9, join: "round" })
}
+
+/** The ghost of a building or a home about to be placed, drawn into `g` around the centre of its footprint. */
+export const drawGhost = (g: Graphics, what: KindId | "home", x: number, y: number) => {
+ const size = what === "home" ? 1 : kinds[what].size
+ const centre = toScreen(x + size / 2, y + size / 2)
+ g.translateTransform(centre.x, centre.y)
+ if (what === "home") drawHouse(g, 1, 1, { right: false, left: false })
+ else drawBuilding(g, kinds[what], 1, 0, 0, { right: false, left: false }, 0xb9beb5)
+ g.resetTransform()
+}
diff --git a/src/content.ts b/src/content.ts
new file mode 100644
index 0000000..792a284
--- /dev/null
+++ b/src/content.ts
@@ -0,0 +1,282 @@
+/**
+ * What the town is made of, as plain data: goods, the buildings that
+ * gather, make, store, and hand them out, and the tiers of homes. Costs,
+ * upkeep, and taxes are in coins; durations in seconds, turned into whole
+ * simulation steps by `ticks`. `archetypes.ts` turns each entry into the
+ * components an entity is spawned with; nothing here knows about the ECS.
+ */
+
+/** The simulation's fixed step. */
+export const STEP_SECONDS = 1 / 60
+export const ticks = (seconds: number): number => Math.round(seconds / STEP_SECONDS)
+
+// ── Goods ─────────────────────────────────────────────────────────────────
+
+export const goodIds = ["wood", "planks", "stone", "ore", "tools", "fish", "wheat", "flour", "bread", "wool", "cloth"] as const
+export type GoodId = (typeof goodIds)[number]
+
+/** Each good's crate label colour (the only colour a good has), and what traders pay for one. */
+export const goods: Readonly<Record<GoodId, { readonly title: string; readonly color: number; readonly price: number }>> = {
+ wood: { title: "wood", color: 0x8a6a45, price: 1 },
+ planks: { title: "planks", color: 0xd27a34, price: 3 },
+ stone: { title: "stone", color: 0x8f9891, price: 2 },
+ ore: { title: "ore", color: 0x5a6479, price: 3 },
+ tools: { title: "tools", color: 0x3d4943, price: 10 },
+ fish: { title: "fish", color: 0x2f8c87, price: 2 },
+ wheat: { title: "wheat", color: 0xd6ae2e, price: 1 },
+ flour: { title: "flour", color: 0xc9b48a, price: 2 },
+ bread: { title: "bread", color: 0xc4523f, price: 4 },
+ wool: { title: "wool", color: 0xa7ada4, price: 2 },
+ cloth: { title: "cloth", color: 0x8a58a8, price: 6 }
+}
+
+/**
+ * Trade: at every collection, traders buy what the town sells beyond the
+ * reserve it keeps, up to `TRADE_LOAD` of each good.
+ */
+export const TRADE_LOAD = 12
+export const RESERVES = [10, 25, 50, 100] as const
+export const trade = { sells: ["wood", "stone", "wheat", "wool"] as ReadonlyArray<GoodId>, reserve: 25 }
+
+export type Amounts = Readonly<Record<GoodId, number>>
+export const none: Amounts = { wood: 0, planks: 0, stone: 0, ore: 0, tools: 0, fish: 0, wheat: 0, flour: 0, bread: 0, wool: 0, cloth: 0 }
+export const amounts = (some: Partial<Record<GoodId, number>>): Amounts => ({ ...none, ...some })
+export const total = (a: Amounts): number => goodIds.reduce((sum, g) => sum + a[g], 0)
+/** Amounts made good by good. */
+export const each = (f: (good: GoodId) => number): Amounts => {
+ const out: Record<GoodId, number> = { ...none }
+ for (const g of goodIds) out[g] = f(g)
+ return out
+}
+
+/** Goods a market walker hands out to homes. */
+export const provisions: ReadonlyArray<GoodId> = ["fish", "bread", "cloth"]
+/** Goods the top bar shows, in order. */
+export const shownGoods: ReadonlyArray<GoodId> = ["wood", "planks", "stone", "tools", "fish", "bread", "cloth"]
+
+// ── Buildings ─────────────────────────────────────────────────────────────
+
+export type Category = "storage" | "gathering" | "crafts" | "food" | "services"
+export const categoryOrder: ReadonlyArray<Category> = ["storage", "gathering", "crafts", "food", "services"]
+
+/** Awnings are coloured by what a building is for. */
+export const categoryColor: Readonly<Record<Category, number>> = {
+ storage: 0x8a58a8,
+ gathering: 0x6e8f36,
+ crafts: 0xd27a34,
+ food: 0xd6ae2e,
+ services: 0x3d6db5
+}
+export const homeColor = 0xc4523f
+
+/** What a gatherer takes from the land around it. */
+export type Source = "tree" | "stone" | "ore" | "field" | "water"
+export type ServiceId = "goods" | "faith"
+
+export type Topper = "none" | "chimney" | "flag" | "cupola" | "sails" | "crates"
+
+export const kindIds = [
+ "townhall", "warehouse", "lumberjack", "forester", "quarry", "mine", "fishery", "sawmill",
+ "smithy", "farm", "mill", "bakery", "sheep", "weaver", "market", "chapel"
+] as const
+export type KindId = (typeof kindIds)[number]
+
+export interface Kind {
+ readonly id: KindId
+ readonly title: string
+ readonly blurb: string
+ readonly category: Category
+ /** Cells a side. */
+ readonly size: 2 | 3
+ // ── Look (see `art.ts`) ──
+ /** Half the building's width, in units: its walls stand this far from its centre. */
+ readonly half: number
+ readonly stories: 1 | 2
+ readonly roof: "flat" | "gable"
+ /** A flat roof is split into bays × bays squares, each `window` units across but the topper's. */
+ readonly bays: 2 | 3
+ readonly window: number
+ readonly topper: Topper
+ // ── Economy ──
+ readonly cost: { readonly coins: number; readonly materials: Partial<Record<GoodId, number>> }
+ /** Coins a minute while it stands. */
+ readonly upkeep: number
+ readonly workers: number
+ /** Residents (and of them citizens) the town needs before it can be built. */
+ readonly unlock: { readonly residents: number; readonly citizens: number }
+ /** In the build menu (the town hall is not). */
+ readonly buildable: boolean
+ // ── Roles: each one present becomes a component ──
+ /** Turns `inputs` of `input` (or nothing, or the land) into `batch` of `output` per job. */
+ readonly recipe?: { readonly input: GoodId | null; readonly inputs: number; readonly output: GoodId; readonly batch: number; readonly seconds: number }
+ /** A gatherer's job needs this within `radius` cells of its footprint. */
+ readonly gathers?: { readonly source: Source; readonly radius: number }
+ /** Plants trees or fields within `radius`, one every `seconds`, up to `max` at once. */
+ readonly plants?: { readonly what: "tree" | "field"; readonly radius: number; readonly seconds: number; readonly max: number }
+ /** Holds goods: every good (storage), or just some (a market). */
+ readonly holds?: { readonly accepts: ReadonlyArray<GoodId> | "all"; readonly cap: number }
+ /** Carriers it sends out at once. */
+ readonly carriers?: number
+ /** Sends a walker down the roads every `seconds`, `range` cells out. */
+ readonly service?: { readonly service: ServiceId; readonly seconds: number; readonly range: number }
+}
+
+const free = { residents: 0, citizens: 0 }
+
+// Each flat-roofed kind's `half` splits evenly into its bays (2 × half / bays
+// is whole), so every window and topper sits on whole units.
+export const kinds: Readonly<Record<KindId, Kind>> = {
+ townhall: {
+ id: "townhall", title: "Town hall", blurb: "the heart of the town: storage, taxes, and a walker with provisions",
+ category: "storage", size: 3, half: 20, stories: 2, roof: "flat", bays: 2, window: 8, topper: "flag",
+ cost: { coins: 0, materials: {} }, upkeep: 0, workers: 0, unlock: free, buildable: false,
+ holds: { accepts: "all", cap: 100 }, carriers: 6,
+ service: { service: "goods", seconds: 8, range: 20 }
+ },
+ warehouse: {
+ id: "warehouse", title: "Warehouse", blurb: "stores goods nearer where they are made and used",
+ category: "storage", size: 3, half: 18, stories: 1, roof: "flat", bays: 3, window: 6, topper: "crates",
+ cost: { coins: 150, materials: { planks: 8, stone: 4 } }, upkeep: 6, workers: 2, unlock: free, buildable: true,
+ holds: { accepts: "all", cap: 50 }, carriers: 4
+ },
+ lumberjack: {
+ id: "lumberjack", title: "Lumberjack", blurb: "fells grown trees nearby for wood",
+ category: "gathering", size: 2, half: 10, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
+ cost: { coins: 50, materials: { planks: 2 } }, upkeep: 3, workers: 2, unlock: free, buildable: true,
+ recipe: { input: null, inputs: 0, output: "wood", batch: 1, seconds: 6 }, gathers: { source: "tree", radius: 4 }, carriers: 2
+ },
+ forester: {
+ id: "forester", title: "Forester", blurb: "plants trees on free ground nearby",
+ category: "gathering", size: 2, half: 9, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
+ cost: { coins: 40, materials: { planks: 2 } }, upkeep: 2, workers: 1, unlock: free, buildable: true,
+ plants: { what: "tree", radius: 3, seconds: 6, max: 20 }
+ },
+ quarry: {
+ id: "quarry", title: "Quarry", blurb: "cuts stone from rocks nearby",
+ category: "gathering", size: 2, half: 10, stories: 1, roof: "flat", bays: 2, window: 6, topper: "none",
+ cost: { coins: 80, materials: { planks: 4 } }, upkeep: 5, workers: 3, unlock: free, buildable: true,
+ recipe: { input: null, inputs: 0, output: "stone", batch: 1, seconds: 8 }, gathers: { source: "stone", radius: 3 }, carriers: 2
+ },
+ mine: {
+ id: "mine", title: "Mine", blurb: "digs ore from a deposit nearby",
+ category: "gathering", size: 2, half: 10, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
+ cost: { coins: 200, materials: { planks: 6, stone: 4 } }, upkeep: 10, workers: 4, unlock: { residents: 0, citizens: 10 }, buildable: true,
+ recipe: { input: null, inputs: 0, output: "ore", batch: 1, seconds: 10 }, gathers: { source: "ore", radius: 3 }, carriers: 2
+ },
+ fishery: {
+ id: "fishery", title: "Fishery", blurb: "catches fish; needs water within two cells",
+ category: "food", size: 2, half: 10, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
+ cost: { coins: 60, materials: { planks: 3 } }, upkeep: 3, workers: 2, unlock: free, buildable: true,
+ recipe: { input: null, inputs: 0, output: "fish", batch: 1, seconds: 4 }, gathers: { source: "water", radius: 2 }, carriers: 2
+ },
+ sawmill: {
+ id: "sawmill", title: "Sawmill", blurb: "saws wood into planks",
+ category: "crafts", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
+ cost: { coins: 100, materials: { planks: 2, stone: 2 } }, upkeep: 6, workers: 2, unlock: free, buildable: true,
+ recipe: { input: "wood", inputs: 1, output: "planks", batch: 1, seconds: 5 }, holds: { accepts: ["wood", "planks"], cap: 8 }, carriers: 2
+ },
+ smithy: {
+ id: "smithy", title: "Smithy", blurb: "forges ore into tools",
+ category: "crafts", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
+ cost: { coins: 250, materials: { planks: 4, stone: 6 } }, upkeep: 12, workers: 3, unlock: { residents: 0, citizens: 10 }, buildable: true,
+ recipe: { input: "ore", inputs: 1, output: "tools", batch: 1, seconds: 10 }, holds: { accepts: ["ore", "tools"], cap: 8 }, carriers: 2
+ },
+ farm: {
+ id: "farm", title: "Farm", blurb: "sows fields around it and harvests the wheat",
+ category: "food", size: 3, half: 12, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
+ cost: { coins: 120, materials: { planks: 4 } }, upkeep: 5, workers: 2, unlock: { residents: 30, citizens: 0 }, buildable: true,
+ recipe: { input: null, inputs: 0, output: "wheat", batch: 1, seconds: 4 }, gathers: { source: "field", radius: 2 },
+ plants: { what: "field", radius: 2, seconds: 3, max: 8 }, carriers: 2
+ },
+ mill: {
+ id: "mill", title: "Mill", blurb: "grinds wheat into flour",
+ category: "food", size: 2, half: 8, stories: 2, roof: "flat", bays: 2, window: 4, topper: "sails",
+ cost: { coins: 150, materials: { planks: 6, stone: 2, tools: 2 } }, upkeep: 8, workers: 2, unlock: { residents: 30, citizens: 0 }, buildable: true,
+ recipe: { input: "wheat", inputs: 1, output: "flour", batch: 1, seconds: 6 }, holds: { accepts: ["wheat", "flour"], cap: 8 }, carriers: 2
+ },
+ bakery: {
+ id: "bakery", title: "Bakery", blurb: "bakes flour into bread",
+ category: "food", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
+ cost: { coins: 150, materials: { planks: 4, stone: 4, tools: 2 } }, upkeep: 8, workers: 2, unlock: { residents: 30, citizens: 0 }, buildable: true,
+ recipe: { input: "flour", inputs: 1, output: "bread", batch: 2, seconds: 6 }, holds: { accepts: ["flour", "bread"], cap: 8 }, carriers: 2
+ },
+ sheep: {
+ id: "sheep", title: "Sheep farm", blurb: "shears sheep for wool",
+ category: "crafts", size: 3, half: 12, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
+ cost: { coins: 100, materials: { planks: 4 } }, upkeep: 5, workers: 2, unlock: { residents: 15, citizens: 0 }, buildable: true,
+ recipe: { input: null, inputs: 0, output: "wool", batch: 1, seconds: 8 }, carriers: 2
+ },
+ weaver: {
+ id: "weaver", title: "Weaver", blurb: "weaves wool into cloth",
+ category: "crafts", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "none",
+ cost: { coins: 150, materials: { planks: 4, stone: 2, tools: 2 } }, upkeep: 8, workers: 2, unlock: { residents: 15, citizens: 0 }, buildable: true,
+ recipe: { input: "wool", inputs: 1, output: "cloth", batch: 1, seconds: 8 }, holds: { accepts: ["wool", "cloth"], cap: 8 }, carriers: 2
+ },
+ market: {
+ id: "market", title: "Market", blurb: "a walker carries fish, bread, and cloth to the homes it passes",
+ category: "services", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "flag",
+ cost: { coins: 120, materials: { planks: 6, stone: 2 } }, upkeep: 6, workers: 2, unlock: free, buildable: true,
+ holds: { accepts: ["fish", "bread", "cloth"], cap: 8 },
+ service: { service: "goods", seconds: 6, range: 18 }
+ },
+ chapel: {
+ id: "chapel", title: "Chapel", blurb: "a walker brings faith to the homes it passes",
+ category: "services", size: 2, half: 12, stories: 2, roof: "flat", bays: 2, window: 6, topper: "cupola",
+ cost: { coins: 200, materials: { planks: 6, stone: 6 } }, upkeep: 10, workers: 1, unlock: { residents: 15, citizens: 0 }, buildable: true,
+ service: { service: "faith", seconds: 8, range: 22 }
+ }
+}
+
+export const kindOrder: ReadonlyArray<KindId> = [
+ "warehouse", "lumberjack", "forester", "quarry", "mine", "sawmill", "smithy", "sheep", "weaver",
+ "fishery", "farm", "mill", "bakery", "market", "chapel"
+]
+
+export const costText = (cost: Kind["cost"]): string =>
+ [cost.coins > 0 ? `${cost.coins} coins` : "", ...Object.entries(cost.materials).map(([g, n]) => `${n} ${g}`)].filter((s) => s !== "").join(" · ")
+
+// ── Homes ─────────────────────────────────────────────────────────────────
+
+export type Tier = 1 | 2
+/** What a home can be short of. Settlers need food (fish or bread); citizens bread, cloth, and faith. */
+export type Need = "food" | "bread" | "cloth" | "faith"
+
+export const home = {
+ /** Half the house's width, in units: a 1×1 cell is 8 units from centre to edge. */
+ half: 5,
+ cost: { coins: 10, materials: { planks: 1 } } as Kind["cost"],
+ tiers: {
+ 1: { title: "settlers", residents: 4, tax: 1.8, height: 14, needs: ["food"] },
+ 2: { title: "citizens", residents: 8, tax: 3.6, height: 26, needs: ["bread", "cloth", "faith"] }
+ } as Readonly<Record<Tier, { readonly title: string; readonly residents: number; readonly tax: number; readonly height: number; readonly needs: ReadonlyArray<Need> }>>,
+ /** A resident moves in (or out) this often. */
+ settle: ticks(3),
+ /** How long each need stays met after a walker's visit: cloth and faith last longer than a meal. */
+ lasts: { food: ticks(60), bread: ticks(60), cloth: ticks(150), faith: ticks(90) } as Readonly<Record<Need, number>>
+}
+
+/** Tax rates the town can set, in percent of the usual. */
+export const TAX_STEPS = [50, 75, 100, 125, 150, 200] as const
+/**
+ * How a tax rate sits with residents: low taxes make homes hold more people
+ * than their needs alone allow, high ones fewer. 100% is neutral.
+ */
+export const appealOf = (rate: number): number => 1.5 - rate / 200
+
+export const needTitle: Readonly<Record<Need, string>> = { food: "food", bread: "bread", cloth: "cloth", faith: "faith" }
+
+// ── The town ──────────────────────────────────────────────────────────────
+
+/** How long anything takes to go up once its materials are in. */
+export const BUILD_TICKS = ticks(2.4)
+/** Taxes are collected and upkeep paid this often. */
+export const LEDGER_TICKS = ticks(10)
+export const ROAD_COST = 2
+/** A new town's treasury and the goods in its town hall. */
+export const start = {
+ coins: 1500,
+ stock: amounts({ wood: 10, planks: 40, stone: 16, tools: 8, fish: 20 })
+}
+/** Trees and fields are ready to harvest once this grown. */
+export const GROWN = { tree: ticks(40), field: ticks(20) }
+export const ROCK_AMOUNT = 40
diff --git a/src/factory.css b/src/factory.css
index 02aa940..da9d514 100644
--- a/src/factory.css
+++ b/src/factory.css
@@ -3,9 +3,22 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
#app { position: fixed; inset: 0; }
#app canvas { display: block; }
-.hud { position: fixed; top: 14px; left: 16px; pointer-events: none; font-size: 12px; line-height: 1.6; }
-.hud h1 { margin: 0 0 2px; font-size: 13px; font-weight: 600; letter-spacing: 0.02em; }
-.hud .stats { color: #6c766f; }
+.hud { position: fixed; top: 12px; left: 16px; display: flex; flex-direction: column; align-items: flex-start; gap: 6px; font-size: 12px; cursor: pointer; max-width: calc(100vw - 32px); }
+.card {
+ display: flex; align-items: stretch; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 6px;
+ box-shadow: 0 2px 0 #dfe2db; overflow: hidden;
+}
+.card .cell { display: flex; align-items: center; gap: 12px; padding: 6px 12px; white-space: nowrap; }
+.card .cell + .cell { border-left: 1px solid #d5d9d0; }
+.hud .bar { font-size: 13px; }
+.hud .coins b { font-size: 15px; font-weight: 700; }
+.hud .coins.debt b { color: #b04a39; }
+.hud .up { color: #4f8a3e; }
+.hud .down { color: #b04a39; }
+.hud .stock { color: #3d4943; flex-wrap: wrap; }
+.hud .good { display: inline-flex; align-items: center; gap: 5px; }
+.hud .good .label { width: 8px; height: 8px; display: inline-block; }
+.hud .good .count { min-width: 2ch; font-weight: 600; }
.toolbar {
position: fixed; left: 16px; bottom: calc(14px + env(safe-area-inset-bottom));
@@ -27,14 +40,10 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
padding: 5px 10px; border-radius: 2px; white-space: pre; transform: translate(14px, 10px); display: none;
}
.toast {
- position: fixed; top: 14px; left: 50%; transform: translateX(-50%); background: #3d4943; color: #f7f8f4;
+ position: fixed; bottom: calc(68px + env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); background: #3d4943; color: #f7f8f4;
font-size: 12px; padding: 6px 12px; border-radius: 3px; opacity: 0; transition: opacity 160ms ease; pointer-events: none;
}
.toast.show { opacity: 1; }
-.hint { position: fixed; right: 16px; transition: opacity 200ms ease; top: 14px; font-size: 11px; color: #8a938c; text-align: right; line-height: 1.6; pointer-events: none; }
-@media (max-width: 900px), (pointer: coarse) { .hint { display: none; } }
-
-body:has(.panel.open) .hint { opacity: 0; }
.panel {
position: fixed; top: 0; right: 0; bottom: 0; width: 360px; max-width: 46vw; box-sizing: border-box;
@@ -49,7 +58,7 @@ body:has(.panel.open) .hint { opacity: 0; }
.panel .sub.warn { color: #b04a39; }
.panel section { margin-top: 24px; }
.panel h3 {
- margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid #d3d7ce; font-size: 11px; font-weight: 400;
+ margin: 0 0 8px; padding-bottom: 8px; border-bottom: 2px solid #d3d7ce; font-size: 11px; font-weight: 400;
letter-spacing: 0.12em; text-transform: uppercase; color: #77817a;
}
.panel .row { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; padding: 4px 0; }
@@ -71,6 +80,8 @@ body:has(.panel.open) .hint { opacity: 0; }
}
.panel .option:hover:not(:disabled) { background: #e6e9e2; }
.panel .option:disabled { opacity: 0.4; cursor: default; }
+.panel .option.short .blurb { color: #b04a39; }
+.panel .option .count { white-space: normal; text-align: right; }
.panel .option .row { padding: 0; }
.panel .option .name { text-decoration: underline; text-decoration-color: #b5bbb2; text-underline-offset: 4px; }
.panel .option .blurb { display: block; margin-top: 4px; color: #77817a; }
@@ -80,3 +91,15 @@ body:has(.panel.open) .hint { opacity: 0; }
.panel section { margin-top: 14px; }
.panel .option { padding: 5px 8px; }
}
+
+.panel .spark { margin-top: 8px; height: 36px; border-bottom: 1px solid #e0e3db; }
+.panel .spark svg { width: 100%; height: 36px; display: block; }
+.panel .lever .controls { display: inline-flex; align-items: center; gap: 8px; }
+.panel .lever .rate { min-width: 4.5ch; text-align: center; font-weight: 600; }
+.panel .frame.step { padding: 2px 10px; }
+.panel .need { display: grid; grid-template-columns: 5ch 1fr 8ch; align-items: center; gap: 10px; padding: 4px 0; }
+.panel .need .track { height: 6px; border: 1px solid #c9cec4; border-radius: 1px; }
+.panel .need .fill { display: block; height: 100%; background: #3d4943; }
+.panel .need .count { text-align: right; }
+.panel .good-row { cursor: pointer; }
+.panel .good-row input { margin: 0 8px 0 0; accent-color: #3d4943; vertical-align: -2px; }
diff --git a/src/grid.ts b/src/grid.ts
new file mode 100644
index 0000000..9550e8b
--- /dev/null
+++ b/src/grid.ts
@@ -0,0 +1,177 @@
+/**
+ * The grid as the town uses it: what stands on each cell, where a tile meets
+ * the road, the land around a building, and the paths walkers take. Plain
+ * functions over a `GridValue` (see `schema.ts`), rebuilt from the tiles
+ * each step.
+ */
+import { GRID, inside, type Point } from "./iso.ts"
+import type { GridValue, Use } from "./schema.ts"
+
+export const key = (x: number, y: number): number => y * GRID + x
+export const cellOf = (k: number): Point => ({ x: k % GRID, y: Math.floor(k / GRID) })
+
+/** +x, +y, -x, -y: the order every search tries neighbours in, so paths are deterministic. */
+export const DIRS: ReadonlyArray<Point> = [{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 0, y: -1 }]
+
+export interface TileLike {
+ readonly x: number
+ readonly y: number
+ readonly size: number
+}
+
+export type { Use }
+
+/** A grid being filled in: tiles are claimed one by one, and placement checks see the claims so far. */
+export class GridBuilder {
+ readonly owner: Array<number> = new Array(GRID * GRID).fill(0)
+ readonly use: Array<Use> = new Array(GRID * GRID).fill("empty")
+
+ claim(tile: TileLike, id: number, use: Use) {
+ for (const c of cellsOf(tile)) {
+ const k = key(c.x, c.y)
+ this.owner[k] = id
+ this.use[k] = use
+ }
+ }
+
+ free(tile: TileLike) {
+ for (const c of cellsOf(tile)) {
+ const k = key(c.x, c.y)
+ this.owner[k] = 0
+ this.use[k] = "empty"
+ }
+ }
+
+ value(): GridValue {
+ return { owner: this.owner, use: this.use }
+ }
+}
+
+export const cellsOf = (tile: TileLike): Array<Point> => {
+ const out: Array<Point> = []
+ for (let dy = 0; dy < tile.size; dy++) for (let dx = 0; dx < tile.size; dx++) out.push({ x: tile.x + dx, y: tile.y + dy })
+ return out
+}
+
+export const useAt = (grid: GridValue, x: number, y: number): Use => (inside(x, y) ? grid.use[key(x, y)]! : "water")
+export const ownerAt = (grid: GridValue, x: number, y: number): number => (inside(x, y) ? grid.owner[key(x, y)]! : 0)
+export const isRoad = (grid: GridValue, x: number, y: number): boolean => inside(x, y) && grid.use[key(x, y)] === "road"
+
+/** Every cell of a tile is on the map and empty, or (when building) only trees, which are felled. */
+export const canPlace = (grid: GridValue, tile: TileLike): boolean =>
+ cellsOf(tile).every((c) => inside(c.x, c.y) && (grid.use[key(c.x, c.y)] === "empty" || grid.use[key(c.x, c.y)] === "tree"))
+
+/** The cells around a tile, out to `radius`, nearest rings first. */
+export const around = (tile: TileLike, radius: number): Array<Point> => {
+ const out: Array<Point> = []
+ for (let r = 1; r <= radius; r++) {
+ for (let y = tile.y - r; y < tile.y + tile.size + r; y++) {
+ for (let x = tile.x - r; x < tile.x + tile.size + r; x++) {
+ const ring = Math.max(tile.x - x, x - (tile.x + tile.size - 1), tile.y - y, y - (tile.y + tile.size - 1))
+ if (ring === r && inside(x, y)) out.push({ x, y })
+ }
+ }
+ }
+ return out
+}
+
+/** Which side of a tile an entrance is on: +x (0), +y (1), -x (2), -y (3). */
+export interface Entrance extends Point {
+ readonly side: 0 | 1 | 2 | 3
+}
+
+/**
+ * Where a tile meets the road: the cells just outside the middle of each
+ * side (the middle two, on an even side). A building's door stands centred
+ * on a side a road meets there.
+ */
+export const entrances = (tile: TileLike): ReadonlyArray<Entrance> => {
+ const lo = Math.floor((tile.size - 1) / 2)
+ const hi = Math.ceil((tile.size - 1) / 2)
+ const out: Array<Entrance> = []
+ for (let o = lo; o <= hi; o++) {
+ out.push(
+ { x: tile.x + tile.size, y: tile.y + o, side: 0 },
+ { x: tile.x + o, y: tile.y + tile.size, side: 1 },
+ { x: tile.x - 1, y: tile.y + o, side: 2 },
+ { x: tile.x + o, y: tile.y - 1, side: 3 }
+ )
+ }
+ return out
+}
+
+/** The entrances with a road on them. */
+export const doors = (grid: GridValue, tile: TileLike): ReadonlyArray<Entrance> =>
+ entrances(tile).filter((c) => isRoad(grid, c.x, c.y))
+
+/** Distances along the road from a set of road cells, and the way back to them. */
+export interface Reach {
+ readonly distance: Int32Array
+ readonly previous: Int32Array
+}
+
+export const reach = (grid: GridValue, from: ReadonlyArray<Point>): Reach => {
+ const distance = new Int32Array(GRID * GRID).fill(-1)
+ const previous = new Int32Array(GRID * GRID).fill(-1)
+ const queue: Array<number> = []
+ for (const c of from) {
+ if (!isRoad(grid, c.x, c.y)) continue
+ const k = key(c.x, c.y)
+ if (distance[k] !== -1) continue
+ distance[k] = 0
+ queue.push(k)
+ }
+ for (let head = 0; head < queue.length; head++) {
+ const k = queue[head]!
+ const c = cellOf(k)
+ for (const d of DIRS) {
+ const nx = c.x + d.x
+ const ny = c.y + d.y
+ if (!isRoad(grid, nx, ny)) continue
+ const n = key(nx, ny)
+ if (distance[n] !== -1) continue
+ distance[n] = distance[k]! + 1
+ previous[n] = k
+ queue.push(n)
+ }
+ }
+ return { distance, previous }
+}
+
+/** The nearest of `to` that `reach` got to, and how far it is. */
+export const nearest = (r: Reach, to: ReadonlyArray<Point>): { readonly cell: Point; readonly distance: number } | null => {
+ let best: { cell: Point; distance: number } | null = null
+ for (const c of to) {
+ const d = r.distance[key(c.x, c.y)]!
+ if (d >= 0 && (best === null || d < best.distance)) best = { cell: { x: c.x, y: c.y }, distance: d }
+ }
+ return best
+}
+
+/** The road cells from where `reach` started to `to`, both ends included. */
+export const pathTo = (r: Reach, to: Point): Array<Point> => {
+ const path: Array<Point> = []
+ for (let k = key(to.x, to.y); k !== -1; k = r.previous[k]!) path.push(cellOf(k))
+ return path.reverse()
+}
+
+/** A straight run, or an L along the longer side first, from `a` to `b`. */
+export const lPath = (a: Point, b: Point): Array<Point> => {
+ const out: Array<Point> = []
+ const corner = Math.abs(b.x - a.x) >= Math.abs(b.y - a.y) ? { x: b.x, y: a.y } : { x: a.x, y: b.y }
+ const walk = (from: Point, to: Point) => {
+ const dx = Math.sign(to.x - from.x)
+ const dy = Math.sign(to.y - from.y)
+ let x = from.x
+ let y = from.y
+ while (x !== to.x || y !== to.y) {
+ out.push({ x, y })
+ x += dx
+ y += dy
+ }
+ }
+ walk(a, corner)
+ walk(corner, b)
+ out.push(b)
+ return out
+}
diff --git a/src/host.ts b/src/host.ts
index 399081a..f575be4 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -1,34 +1,18 @@
/**
- * The page around the yard: the Pixi stage and its layers, the camera (drag
- * to pan, wheel or pinch to zoom), the pointer turned into intents, and the
- * toolbar, stats, tooltip, and toasts.
+ * The page around the town: the Pixi stage and its layers, the camera (drag
+ * to pan, wheel or pinch to zoom), the pointer turned into gestures, and the
+ * top bar, toolbar, build menu, panel, tooltip, and toasts.
*/
import { Application, Container, Graphics } from "pixi.js"
import { drawFloor, type Stage } from "./art.ts"
+import {
+ appealOf, categoryColor, categoryOrder, costText, goodIds, goods, home, kindOrder, kinds, needTitle, RESERVES, ROAD_COST, TAX_STEPS,
+ type GoodId, type Kind, type KindId
+} from "./content.ts"
import { GRID, toScreen, type Point } from "./iso.ts"
-import { kindOrder, kinds } from "./kinds.ts"
-import type { Intent, Mode, PanelLink, UiValue } from "./schema.ts"
-
-/** A small yard to start from, like a repository's packages feeding each other. */
-const demo: ReadonlyArray<Intent> = [
- { type: "place", kind: "source", cell: { x: 2, y: 12 } },
- { type: "place", kind: "source", cell: { x: 3, y: 4 } },
- { type: "place", kind: "plant", cell: { x: 9, y: 9 } },
- { type: "place", kind: "workshop", cell: { x: 10, y: 2 } },
- { type: "place", kind: "workshop", cell: { x: 16, y: 7 } },
- { type: "place", kind: "workshop", cell: { x: 9, y: 16 } },
- { type: "place", kind: "depot", cell: { x: 20, y: 13 } },
- { type: "place", kind: "depot", cell: { x: 16, y: 19 } },
- { type: "link", from: { x: 2, y: 12 }, to: { x: 9, y: 9 } },
- { type: "link", from: { x: 3, y: 4 }, to: { x: 9, y: 9 } },
- { type: "link", from: { x: 3, y: 4 }, to: { x: 10, y: 2 } },
- { type: "link", from: { x: 10, y: 2 }, to: { x: 16, y: 7 } },
- { type: "link", from: { x: 9, y: 9 }, to: { x: 16, y: 7 } },
- { type: "link", from: { x: 9, y: 9 }, to: { x: 9, y: 16 } },
- { type: "link", from: { x: 16, y: 7 }, to: { x: 20, y: 13 } },
- { type: "link", from: { x: 9, y: 16 }, to: { x: 16, y: 19 } }
-]
+import type { Tool, UiValue } from "./ui.ts"
+import { emptyPreview } from "./ui.ts"
const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = "") => {
const node = document.createElement(tag)
@@ -37,7 +21,14 @@ const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, te
return node
}
-export const createHost = async (mount: HTMLElement) => {
+const hex = (color: number) => `#${color.toString(16).padStart(6, "0")}`
+
+export interface Persistence {
+ readonly save: () => string | null
+ readonly load: () => string | null
+}
+
+export const createHost = async (mount: HTMLElement, persistence: () => Persistence) => {
const app = new Application()
await app.init({
resizeTo: window,
@@ -52,18 +43,20 @@ export const createHost = async (mount: HTMLElement) => {
const world = new Container()
const floor = new Graphics()
drawFloor(floor)
+ const ground = new Graphics()
const plates = new Container()
- const belts = new Container()
+ const roads = new Graphics()
const preview = new Container()
const overlay = new Graphics()
preview.addChild(overlay)
const objects = new Container({ sortableChildren: true })
const ghost = new Graphics()
+ ghost.zIndex = 1e6
objects.addChild(ghost)
const labels = new Container()
- world.addChild(floor, plates, belts, preview, objects, labels)
+ world.addChild(floor, ground, plates, roads, preview, objects, labels)
app.stage.addChild(world)
- const stage: Stage = { world, plates, belts, preview, objects, labels, overlay, ghost }
+ const stage: Stage = { world, ground, plates, roads, preview, objects, labels, overlay, ghost }
// ── Camera ──
const centre = toScreen(GRID / 2, GRID / 2)
@@ -74,7 +67,6 @@ export const createHost = async (mount: HTMLElement) => {
const look = { x: centre.x, y: centre.y }
const placeCamera = () => {
world.scale.set(zoom)
- // Whole device pixels, so lines land where the lattice puts them.
const dpr = app.renderer.resolution
world.position.set(
Math.round((app.screen.width / 2 - look.x * zoom) * dpr) / dpr,
@@ -92,97 +84,169 @@ export const createHost = async (mount: HTMLElement) => {
placeCamera()
}
- /** Glides the camera to a world point, leaving room for the panel on the right. */
- let glide: Point | null = null
- const lookAt = (at: Point) => {
- glide = { x: at.x + panelWidth() / 2 / zoom, y: at.y - 30 }
- }
-
// ── DOM ──
+ // The top bar: treasury, people, and jobs in one strip; the goods in stock below, grouped.
const hud = el("div", "hud")
- const title = el("h1", "", "factory yard")
- const stats = el("div", "stats")
- hud.append(title, stats)
- const hint = el("div", "hint")
- hint.innerHTML = "tap the ground: build there<br>tap a factory: what it takes and feeds<br>drag factory → factory: belt<br>drag empty ground: pan · wheel: zoom<br>X bulldoze · Esc close"
+ const bar = el("div", "card bar")
+ const coins = el("div", "cell coins")
+ const people = el("div", "cell")
+ const jobs = el("div", "cell")
+ bar.append(coins, people, jobs)
+ const stock = el("div", "card stock")
+ const groups: ReadonlyArray<ReadonlyArray<GoodId>> = [["wood", "planks", "stone", "tools"], ["fish", "bread"], ["wool", "cloth"]]
+ const goodCells = new Map<GoodId, HTMLElement>()
+ for (const group of groups) {
+ const cell = el("div", "cell")
+ for (const g of group) {
+ const item = el("span", "good")
+ const swatch = el("span", "label")
+ swatch.style.background = hex(goods[g].color)
+ const count = el("span", "count", "0")
+ item.append(swatch, document.createTextNode(goods[g].title), count)
+ cell.append(item)
+ goodCells.set(g, count)
+ }
+ stock.append(cell)
+ }
+ hud.append(bar, stock)
+ hud.title = "Open the town's numbers and taxes"
+ hud.onclick = () => toggleMenu("town")
const tooltip = el("div", "tooltip")
const toastBox = el("div", "toast")
const toolbar = el("div", "toolbar")
const panel = el("aside", "panel")
- document.body.append(hud, hint, tooltip, toastBox, toolbar, panel)
- const panelWidth = () => (panel.classList.contains("open") ? panel.offsetWidth : 0)
+ document.body.append(hud, tooltip, toastBox, toolbar, panel)
let toastTimer = 0
const ui: UiValue = {
- mode: "select",
- plot: null,
- plotKind: null,
- linkFrom: null,
+ tool: "select",
+ placing: null,
+ menu: null,
pointer: null,
dragFrom: null,
selected: null,
- intents: [...demo],
- preview: { ghost: null, plots: [], path: null, hoverFactory: null, hoverBelt: null, focus: null, danger: false, tooltip: null },
+ gestures: [],
+ edits: [{ type: "newTown", seed: (Date.now() & 0x7fffffff) >>> 0 }],
+ preview: emptyPreview(),
hits: [],
panel: null,
centres: new Map(),
- stats: { factories: 0, belts: 0, crates: 0, shipped: 0 },
+ stats: null,
toast: (message) => {
toastBox.textContent = message
toastBox.classList.add("show")
window.clearTimeout(toastTimer)
- toastTimer = window.setTimeout(() => toastBox.classList.remove("show"), 1600)
+ toastTimer = window.setTimeout(() => toastBox.classList.remove("show"), 1800)
}
}
- const tools: ReadonlyArray<{ readonly mode: Mode; readonly label: string; readonly key: string }> = [
- { mode: "select", label: "select", key: "S" },
- { mode: "bulldoze", label: "bulldoze", key: "X" }
+ const tools: ReadonlyArray<{ readonly tool: Tool | "build" | "town"; readonly label: string; readonly key: string; readonly swatch: string; readonly tip: string }> = [
+ { tool: "select", label: "select", key: "S", swatch: "round", tip: "Click a building or home to see what it does · drag to pan · wheel to zoom" },
+ { tool: "road", label: "road", key: "R", swatch: "#e6e8e2", tip: `Drag to lay a road · ${ROAD_COST} coins a cell` },
+ { tool: "home", label: "homes", key: "H", swatch: "#c4523f", tip: `Drag to lay a row of homes along a road · ${costText(home.cost)} each` },
+ { tool: "build", label: "build", key: "B", swatch: "#3d6db5", tip: "Choose a building, then click to place it · Esc to stop" },
+ { tool: "bulldoze", label: "bulldoze", key: "X", swatch: "#8f9891", tip: "Click a building, home, road, tree, or field to remove it" },
+ { tool: "town", label: "town", key: "T", swatch: "#8a58a8", tip: "The town's numbers, history, and taxes" }
]
const buttons = tools.map((tool) => {
const button = el("button", "")
+ button.title = tool.tip
const swatch = el("span", "swatch")
- if (tool.mode === "select") swatch.style.borderRadius = "50%"
- if (tool.mode === "bulldoze") swatch.style.background = "#c4523f"
+ if (tool.swatch === "round") swatch.style.borderRadius = "50%"
+ else swatch.style.background = tool.swatch
button.append(swatch, document.createTextNode(tool.label), el("kbd", "", tool.key))
- button.onclick = () => choose(tool.mode)
+ button.onclick = () => (tool.tool === "build" || tool.tool === "town" ? toggleMenu(tool.tool) : choose(tool.tool))
toolbar.append(button)
return { tool, button }
})
toolbar.append(el("span", "sep"))
- const demoButton = el("button", "", "demo")
- demoButton.onclick = () => ui.intents.push({ type: "clear" }, ...demo)
- const clearButton = el("button", "", "clear")
- clearButton.onclick = () => ui.intents.push({ type: "clear" })
- toolbar.append(demoButton, clearButton)
-
- const close = () => {
- ui.selected = null
- ui.plot = null
- ui.plotKind = null
- ui.linkFrom = null
+ const action = (label: string, tip: string, run: () => void) => {
+ const button = el("button", "", label)
+ button.title = tip
+ button.onclick = run
+ toolbar.append(button)
}
+ action("new town", "Found a new town on new land", () => {
+ ui.edits.push({ type: "newTown", seed: (Date.now() & 0x7fffffff) >>> 0 })
+ history.length = 0
+ choose("select")
+ })
+ action("save", "Save the town in this browser", () => ui.toast(persistence().save() ?? "Saved"))
+ action("load", "Load the saved town", () => ui.toast(persistence().load() ?? "Loaded"))
- const choose = (mode: Mode) => {
- ui.mode = mode
+ const refreshTools = () => {
+ for (const { tool, button } of buttons) {
+ const on = tool.tool === "build" ? ui.menu === "build" || ui.tool === "place" : tool.tool === "town" ? ui.menu === "town" : tool.tool === ui.tool
+ button.classList.toggle("on", on)
+ }
+ }
+ const choose = (tool: Tool) => {
+ ui.tool = tool
ui.dragFrom = null
- if (mode === "bulldoze") close()
- for (const { tool, button } of buttons) button.classList.toggle("on", tool.mode === mode)
+ if (tool !== "place") ui.placing = null
+ if (tool !== "select") ui.selected = null
+ refreshTools()
+ }
+ const toggleMenu = (menu: "build" | "town") => {
+ ui.menu = ui.menu === menu ? null : menu
+ if (ui.menu) ui.selected = null
+ refreshTools()
+ }
+ const place = (kind: KindId) => {
+ ui.placing = kind
+ ui.menu = null
+ choose("place")
+ ui.toast(`Click to place a ${kinds[kind].title.toLowerCase()} · Esc to stop`)
}
choose("select")
window.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
- if (ui.linkFrom !== null) ui.linkFrom = null
- else if (ui.mode !== "select") choose("select")
- else close()
+ if (ui.tool !== "select") choose("select")
+ else if (ui.menu) ui.menu = null
+ else ui.selected = null
+ refreshTools()
}
- if (event.key === "s" || event.key === "S") choose("select")
- if (event.key === "x" || event.key === "X") choose("bulldoze")
+ const key = event.key.toLowerCase()
+ if (key === "s") choose("select")
+ if (key === "r") choose("road")
+ if (key === "h") choose("home")
+ if (key === "x") choose("bulldoze")
+ if (key === "b") toggleMenu("build")
+ if (key === "t") toggleMenu("town")
})
+ // ── History, for the town panel's lines ──
+ interface Sample {
+ readonly coins: number
+ readonly residents: number
+ readonly stock: Readonly<Record<GoodId, number>>
+ }
+ /** One sample every `SAMPLE_SECONDS`, the last ten minutes of them. */
+ const history: Array<Sample> = []
+ const SAMPLE_SECONDS = 4
+ const HISTORY = 150
+ window.setInterval(() => {
+ const s = ui.stats
+ if (!s) return
+ history.push({ coins: s.coins, residents: s.settlers + s.citizens, stock: s.stock })
+ if (history.length > HISTORY) history.shift()
+ }, SAMPLE_SECONDS * 1000)
+
+ /** A thin ink line of `values`, scaled to its own range. */
+ const sparkline = (values: ReadonlyArray<number>): string => {
+ if (values.length < 2) return ""
+ const w = 300
+ const h = 36
+ const lo = Math.min(...values)
+ const hi = Math.max(...values)
+ const span = hi - lo || 1
+ const points = values.map((v, i) => `${((i / (values.length - 1)) * w).toFixed(1)},${(h - 2 - ((v - lo) / span) * (h - 4)).toFixed(1)}`).join(" ")
+ return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none"><polyline points="${points}" fill="none" stroke="#3d4943" stroke-width="1.5" vector-effect="non-scaling-stroke"/></svg>`
+ }
+
// ── Panel ──
- /** Volatile numbers the panel shows, updated in place without rebuilding it. */
+ /** Volatile parts of the panel, updated in place without rebuilding it. */
let live: Array<() => void> = []
let shape = ""
@@ -191,28 +255,208 @@ export const createHost = async (mount: HTMLElement) => {
box.append(el("h3", "", heading))
return box
}
+ const header = (title: string) => {
+ const head = el("header", "")
+ const closeButton = el("button", "frame", "Close")
+ closeButton.onclick = () => {
+ ui.selected = null
+ ui.menu = null
+ refreshTools()
+ }
+ head.append(el("h2", "", title), closeButton)
+ return head
+ }
+
+ const lockText = (kind: Kind): string | null => {
+ const s = ui.stats
+ if (!s) return null
+ const residents = s.settlers + s.citizens
+ if (residents < kind.unlock.residents) return `needs ${kind.unlock.residents} residents`
+ if (s.citizens < kind.unlock.citizens) return `needs ${kind.unlock.citizens} citizens`
+ return null
+ }
+ const shortText = (cost: Kind["cost"]): string | null => {
+ const s = ui.stats
+ if (!s) return null
+ if (s.coins < cost.coins) return "not enough coins"
+ for (const [g, n] of Object.entries(cost.materials)) if (s.stock[g as keyof typeof s.stock] < (n ?? 0)) return `not enough ${g}`
+ return null
+ }
- const openFactory = (id: number) => {
- ui.selected = id
- ui.plot = null
- ui.linkFrom = null
- const at = ui.centres.get(id)
- if (at) lookAt(at)
+ const buildMenu = () => {
+ panel.append(header("build"))
+ panel.append(el("p", "sub", `Choose, then click on the map to place · Esc to stop. Roads ${ROAD_COST} coins a cell (R), homes ${costText(home.cost)} (H).`))
+ for (const category of categoryOrder) {
+ const options = kindOrder.filter((id) => kinds[id].category === category && kinds[id].buildable)
+ if (options.length === 0) continue
+ const box = section(category)
+ box.querySelector("h3")!.style.borderBottomColor = hex(categoryColor[category])
+ for (const id of options) {
+ const kind = kinds[id]
+ const option = el("button", "option")
+ const top = el("span", "row")
+ top.append(el("span", "name", kind.title.toLowerCase()), el("span", "count", costText(kind.cost)))
+ const blurb = el("span", "blurb", "")
+ option.append(top, blurb)
+ option.onclick = () => place(id)
+ live.push(() => {
+ const lock = lockText(kind)
+ const short = lock ? null : shortText(kind.cost)
+ option.disabled = lock !== null
+ option.classList.toggle("short", short !== null)
+ blurb.textContent = lock ?? `${kind.blurb} · ${kind.workers} workers · ${kind.upkeep}/min${short ? ` · ${short}` : ""}`
+ })
+ box.append(option)
+ }
+ panel.append(box)
+ }
}
- const factoryRows = (box: HTMLElement, links: ReadonlyArray<PanelLink>, which: "takes" | "feeds") => {
- links.forEach((link, index) => {
- const row = el("div", "row")
- const name = el("button", "link", `${kinds[link.kind].title.toLowerCase()}/${link.name}`)
- name.onclick = () => openFactory(link.id)
- const count = el("span", "count")
- row.append(name, count)
- box.append(row)
+ const row = (box: HTMLElement, label: string) => {
+ const line = el("div", "row")
+ const value = el("span", "count")
+ line.append(el("span", "", label), value)
+ box.append(line)
+ return value
+ }
+
+ const townPanel = () => {
+ panel.append(header("town"))
+ const sub = el("p", "sub")
+ panel.append(sub)
+
+ const treasury = section("treasury")
+ const taxes = row(treasury, "taxes")
+ const traded = row(treasury, "trade")
+ const upkeep = row(treasury, "upkeep")
+ const net = row(treasury, "a minute")
+ const coinLine = el("div", "spark")
+ treasury.append(coinLine)
+ panel.append(treasury)
+
+ const levers = section("taxes")
+ for (const tier of ["settlers", "citizens"] as const) {
+ const line = el("div", "row lever")
+ const minus = el("button", "frame step", "−")
+ const value = el("span", "rate")
+ const plus = el("button", "frame step", "+")
+ const controls = el("span", "controls")
+ controls.append(minus, value, plus)
+ line.append(el("span", "", tier), controls)
+ const effect = el("p", "empty")
+ levers.append(line, effect)
+ const move = (by: number) => {
+ const now = ui.stats?.policy[tier] ?? 100
+ const i = TAX_STEPS.indexOf(now as (typeof TAX_STEPS)[number])
+ const next = TAX_STEPS[Math.min(TAX_STEPS.length - 1, Math.max(0, (i < 0 ? 2 : i) + by))]!
+ ui.edits.push({ type: "tax", tier, rate: next })
+ }
+ minus.onclick = () => move(-1)
+ plus.onclick = () => move(1)
live.push(() => {
- const p = ui.panel
- const now = p?.type === "factory" ? p[which][index] : undefined
- count.textContent = now ? `${now.crates} crate${now.crates === 1 ? "" : "s"}` : ""
+ const rate = ui.stats?.policy[tier] ?? 100
+ value.textContent = `${rate}%`
+ const appeal = Math.round((appealOf(rate) - 1) * 100)
+ effect.textContent = appeal === 0
+ ? "the usual rate"
+ : appeal > 0
+ ? `homes keep up to ${appeal}% more residents when short of needs`
+ : `homes hold ${-appeal}% fewer residents`
})
+ }
+ panel.append(levers)
+
+ const town = section("people")
+ const settlers = row(town, "settlers")
+ const citizens = row(town, "citizens")
+ const homes = row(town, "homes")
+ const work = row(town, "jobs filled")
+ const peopleLine = el("div", "spark")
+ town.append(peopleLine)
+ panel.append(town)
+
+ const needs = section("homes supplied")
+ const bars = (["food", "bread", "cloth", "faith"] as const).map((n) => {
+ const line = el("div", "need")
+ const label = el("span", "", needTitle[n])
+ const track = el("span", "track")
+ const fill = el("span", "fill")
+ track.append(fill)
+ const value = el("span", "count")
+ line.append(label, track, value)
+ needs.append(line)
+ return { n, fill, value }
+ })
+ panel.append(needs)
+
+ const store = section("goods and trade")
+ const reserveLine = el("div", "row lever")
+ const reserveControls = el("span", "controls")
+ const fewer = el("button", "frame step", "−")
+ const reserveValue = el("span", "rate")
+ const more = el("button", "frame step", "+")
+ reserveControls.append(fewer, reserveValue, more)
+ reserveLine.append(el("span", "", "keep before selling"), reserveControls)
+ store.append(reserveLine)
+ const stepReserve = (by: number) => {
+ const now = ui.stats?.policy.reserve ?? 25
+ const i = RESERVES.indexOf(now as (typeof RESERVES)[number])
+ ui.edits.push({ type: "reserve", amount: RESERVES[Math.min(RESERVES.length - 1, Math.max(0, (i < 0 ? 1 : i) + by))]! })
+ }
+ fewer.onclick = () => stepReserve(-1)
+ more.onclick = () => stepReserve(1)
+ store.append(el("p", "empty", "Ticked goods are sold to traders beyond what the town keeps, for the price shown."))
+ const goodRows = goodIds.map((g) => {
+ const line = el("label", "row good-row")
+ const box = el("input", "")
+ box.type = "checkbox"
+ box.onchange = () => ui.edits.push({ type: "sell", good: g, on: box.checked })
+ const name = el("span", "", `${goods[g].title} · ${goods[g].price}c`)
+ const left = el("span", "")
+ left.append(box, name)
+ const value = el("span", "count")
+ line.append(left, value)
+ store.append(line)
+ return { g, value, box }
+ })
+ panel.append(store)
+
+ live.push(() => {
+ const s = ui.stats
+ if (!s) return
+ sub.textContent = `${s.settlers + s.citizens} residents · ${s.coins} coins`
+ taxes.textContent = `+${s.taxes}`
+ traded.textContent = `+${s.trade}`
+ upkeep.textContent = `−${s.upkeep}`
+ net.textContent = `${s.net >= 0 ? "+" : ""}${s.net} coins`
+ settlers.textContent = String(s.settlers)
+ citizens.textContent = String(s.citizens)
+ homes.textContent = String(s.homes)
+ work.textContent = `${s.employed} of ${s.jobs}`
+ for (const b of bars) {
+ const share = s.homes > 0 ? s.needs[b.n] / s.homes : 0
+ b.fill.style.width = `${Math.round(share * 100)}%`
+ b.value.textContent = `${s.needs[b.n]} of ${s.homes}`
+ }
+ // Goods' change over the last minute of samples.
+ const ago = history[Math.max(0, history.length - 1 - Math.round(60 / SAMPLE_SECONDS))]
+ reserveValue.textContent = String(s.policy.reserve)
+ for (const r of goodRows) {
+ const change = ago ? s.stock[r.g] - ago.stock[r.g] : 0
+ r.value.textContent = `${s.stock[r.g]}${change !== 0 ? ` ${change > 0 ? "+" : ""}${change}/min` : ""}`
+ const selling = s.policy.sells.includes(r.g)
+ if (r.box.checked !== selling) r.box.checked = selling
+ }
+ const coinsSvg = sparkline(history.map((h) => h.coins))
+ if (coinLine.dataset.svg !== coinsSvg) {
+ coinLine.dataset.svg = coinsSvg
+ coinLine.innerHTML = coinsSvg
+ }
+ const peopleSvg = sparkline(history.map((h) => h.residents))
+ if (peopleLine.dataset.svg !== peopleSvg) {
+ peopleLine.dataset.svg = peopleSvg
+ peopleLine.innerHTML = peopleSvg
+ }
})
}
@@ -221,85 +465,48 @@ export const createHost = async (mount: HTMLElement) => {
live = []
panel.replaceChildren()
if (!p) return
- const head = el("header", "")
- const closeButton = el("button", "frame", "Close")
- closeButton.onclick = close
- if (p.type === "plot") {
- head.append(el("h2", "", `plot ${p.x},${p.y}`), closeButton)
- panel.append(head, el("p", p.free ? "sub" : "sub warn", p.reason))
- const box = section("build here")
- for (const id of kindOrder) {
- const kind = kinds[id]
- const row = el("button", "option")
- row.disabled = !p.free
- const top = el("span", "row")
- top.append(el("span", "name", kind.title.toLowerCase()), el("span", "count", kind.needs === 0 ? `makes ${kind.makes}` : kind.makes === 0 ? `ships ${kind.needs}` : `takes ${kind.needs}, makes ${kind.makes}`))
- row.append(top, el("span", "blurb", `${kind.blurb} · ${kind.period}s a job`))
- row.onmouseenter = () => (ui.plotKind = id)
- row.onmouseleave = () => {
- if (ui.plotKind === id) ui.plotKind = null
- }
- row.onclick = () => ui.intents.push({ type: "build", kind: id })
- box.append(row)
- }
- panel.append(box)
- return
- }
+ if (p.type === "build") return buildMenu()
+ if (p.type === "town") return townPanel()
- const kind = kinds[p.kind]
- head.append(el("h2", "", `${kind.title.toLowerCase()}/${p.name}`), closeButton)
+ const title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : `${home.tiers[p.tier].title}' home`
const status = el("p", "sub")
- const numbers = el("p", "sub")
- panel.append(head, status, numbers)
+ panel.append(header(title), status)
+ const box = section(p.type === "building" ? "at work" : "household")
+ const rows: Array<HTMLElement> = []
+ panel.append(box)
live.push(() => {
const now = ui.panel
- if (now?.type !== "factory") return
- status.textContent = `${now.status} · ${kind.blurb}`
- numbers.textContent = now.kind === "depot"
- ? `${now.inputs} waiting · ${now.made} shipped`
- : now.kind === "source"
- ? `${now.outputs} ready · ${now.made} made`
- : `${now.inputs} in · ${now.outputs} out · ${now.made} jobs done`
- })
-
- const takes = section("takes from")
- if (kind.needs === 0) takes.append(el("p", "empty", "nothing: it makes crates from nothing"))
- else if (p.takes.length === 0) takes.append(el("p", "empty", "no belts in yet: drag one here from another factory"))
- factoryRows(takes, p.takes, "takes")
- const feeds = section("feeds")
- if (kind.makes === 0) feeds.append(el("p", "empty", "nothing: it ships crates out of the yard"))
- else if (p.feeds.length === 0) feeds.append(el("p", "empty", "no belts out yet: connect it to send its crates on"))
- factoryRows(feeds, p.feeds, "feeds")
- panel.append(takes, feeds)
-
- const actions = el("div", "actions")
- if (kind.makes > 0) {
- const connect = el("button", "frame", p.linking ? "Tap a factory… (cancel)" : "Connect to…")
- connect.onclick = () => {
- ui.linkFrom = p.linking ? null : p.id
- if (!p.linking) ui.toast("Tap the factory to send crates to")
+ if (!now || now.type === "build" || now.type === "town" || now.type !== p.type) return
+ if (now.type === "building") {
+ status.textContent = now.problem ?? `${now.status} · ${kinds[now.kind].blurb}`
+ status.classList.toggle("warn", now.problem !== null)
+ } else status.textContent = now.tier === 1 ? "settlers: fish or bread from a market keeps them" : "citizens: they need bread, cloth, and faith"
+ while (rows.length < now.lines.length) {
+ const line = el("div", "row")
+ rows.push(line)
+ box.append(line)
}
- actions.append(connect)
+ rows.forEach((row, i) => (row.textContent = now.lines[i] ?? ""))
+ })
+ if (!(p.type === "building" && p.kind === "townhall")) {
+ const actions = el("div", "actions")
+ const remove = el("button", "frame danger", "Remove")
+ remove.onclick = () => ui.edits.push({ type: "remove", cell: p.cell })
+ actions.append(remove)
+ panel.append(actions)
}
- const remove = el("button", "frame danger", "Remove")
- remove.onclick = () => ui.intents.push({ type: "remove", factory: p.id })
- actions.append(remove)
- panel.append(actions)
}
- /** Rebuilds the panel when what it lists changes, and refreshes its numbers every frame. */
+ /** Rebuilds the panel when what it shows changes, and refreshes its numbers every frame. */
const syncPanel = () => {
const p = ui.panel
- const next = p === null
- ? ""
- : p.type === "plot"
- ? `plot|${p.x},${p.y}|${p.free}|${p.reason}`
- : `factory|${p.id}|${p.linking}|${p.takes.map((l) => l.id).join(",")}|${p.feeds.map((l) => l.id).join(",")}`
+ const next = p === null ? "" : p.type === "build" || p.type === "town" ? p.type : `${p.type}|${p.id}|${p.type === "house" ? p.tier : ""}`
if (next !== shape) {
shape = next
// Keep the old contents while the closed panel slides away.
if (p !== null) buildPanel()
panel.classList.toggle("open", p !== null)
+ refreshTools()
}
for (const update of live) update()
}
@@ -324,19 +531,15 @@ export const createHost = async (mount: HTMLElement) => {
screenPointer = at
ui.pointer = toWorld(at.x, at.y)
if (pointers.size === 2) {
- // A second finger: pinch, and forget what the first one was doing.
pinch = { distance: spread()!.distance }
press = null
ui.dragFrom = null
return
}
- const world = toWorld(at.x, at.y)
- const onFactory = ui.hits.some((h) => h.contains(world))
- // Dragging from a factory draws a belt; dragging anywhere else pans.
- const pan = event.button === 1 || event.button === 2 || !(ui.mode === "select" && onFactory && ui.linkFrom === null)
- glide = null
+ // Roads and homes are laid by dragging; with any other tool a drag pans.
+ const pan = event.button !== 0 || (ui.tool !== "road" && ui.tool !== "home")
press = { id: event.pointerId, start: at, last: at, pan, panned: false }
- if (event.button === 0) ui.intents.push({ type: "press", at: world })
+ if (event.button === 0) ui.gestures.push({ type: "press", at: toWorld(at.x, at.y) })
})
canvas.addEventListener("pointermove", (event) => {
@@ -364,17 +567,15 @@ export const createHost = async (mount: HTMLElement) => {
const release = (event: PointerEvent, cancelled: boolean) => {
pointers.delete(event.pointerId)
if (pinch && pointers.size < 2) {
- // A pinch settles on the nearest zoom step.
pinch = null
const nearest = zooms.reduce((best, z) => (Math.abs(z - zoom) < Math.abs(best - zoom) ? z : best), zooms[0])
zoomTo(event.clientX, event.clientY, nearest)
}
if (press && press.id === event.pointerId) {
const at = toWorld(event.clientX, event.clientY)
- ui.intents.push({ type: "release", at, panned: press.panned || cancelled || event.button !== 0 })
+ ui.gestures.push({ type: "release", at, panned: press.panned || cancelled || event.button !== 0 })
press = null
}
- // Touch has no hover: clear it when the finger lifts.
if (event.pointerType !== "mouse") {
ui.pointer = null
screenPointer = null
@@ -391,7 +592,6 @@ export const createHost = async (mount: HTMLElement) => {
canvas.addEventListener("contextmenu", (event) => event.preventDefault())
canvas.addEventListener("wheel", (event) => {
event.preventDefault()
- // One wheel notch (or a trackpad's worth of scrolling) is one zoom step.
wheel += event.deltaY
if (Math.abs(wheel) < 40) return
const index = zooms.findIndex((z) => z >= zoom - 1e-6)
@@ -400,17 +600,17 @@ export const createHost = async (mount: HTMLElement) => {
zoomTo(event.clientX, event.clientY, next)
}, { passive: false })
- /** Copies the yard's preview and numbers into the page, once a frame. */
+ /** Copies the town's numbers and preview into the page, once a frame. */
const syncPage = () => {
syncPanel()
- if (glide) {
- look.x += (glide.x - look.x) * 0.14
- look.y += (glide.y - look.y) * 0.14
- if (Math.hypot(glide.x - look.x, glide.y - look.y) < 0.5) glide = null
- placeCamera()
- }
const s = ui.stats
- stats.textContent = `${s.factories} factories · ${s.belts} belts · ${s.crates} in transit · ${s.shipped} shipped`
+ if (s) {
+ coins.innerHTML = `<b>${s.coins}</b> coins <span class="${s.net >= 0 ? "up" : "down"}">${s.net >= 0 ? "+" : ""}${s.net}/min</span>`
+ coins.classList.toggle("debt", s.coins < 0)
+ people.textContent = `${s.settlers} settlers · ${s.citizens} citizens`
+ jobs.textContent = `${s.employed}/${s.jobs} jobs`
+ for (const [g, count] of goodCells) count.textContent = String(s.stock[g])
+ }
const text = ui.preview.tooltip
if (text && screenPointer) {
tooltip.textContent = text
@@ -418,7 +618,7 @@ export const createHost = async (mount: HTMLElement) => {
tooltip.style.left = `${Math.min(screenPointer.x, window.innerWidth - tooltip.offsetWidth - 20)}px`
tooltip.style.top = `${screenPointer.y}px`
} else tooltip.style.display = "none"
- canvas.style.cursor = press?.panned ? "grabbing" : ui.preview.hoverFactory !== null || ui.mode !== "select" ? "pointer" : "default"
+ canvas.style.cursor = press?.panned ? "grabbing" : ui.preview.hover !== null || ui.tool !== "select" ? "pointer" : "default"
}
return { app, stage, ui, syncPage }
diff --git a/src/iso.ts b/src/iso.ts
index 0dc2bdf..e87061b 100644
--- a/src/iso.ts
+++ b/src/iso.ts
@@ -12,7 +12,7 @@ export const TILE_H = 32
/** A sixteenth of a cell: the smallest length anything on the floor is measured in. */
export const U = 1 / 16
/** Cells along each side of the yard. */
-export const GRID = 24
+export const GRID = 32
/** A factory stands on 3×3 cells; belts meet it at the middle cell of a side. */
export const FOOTPRINT = 3
diff --git a/src/kinds.ts b/src/kinds.ts
deleted file mode 100644
index ee90f55..0000000
--- a/src/kinds.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/** The factories the player can place, and how each one works. */
-export type KindId = "source" | "workshop" | "plant" | "depot"
-
-export interface Kind {
- readonly id: KindId
- readonly title: string
- readonly blurb: string
- /** Half the building's width, in units (see `iso.ts`): its walls stand this far from its centre. */
- readonly half: number
- readonly stories: 1 | 2
- /**
- * The roof is split into bays × bays squares: the back one holds the
- * chimney, a depot's flag stands in the right-hand one, and every other
- * one has a window `window` units across.
- */
- readonly bays: 2 | 3
- readonly window: number
- /** Crates taken per job (0: makes them from nothing). */
- readonly needs: number
- /** Crates made per job (0: ships them out of the yard). */
- readonly makes: number
- /** Seconds per job. */
- readonly period: number
- readonly inputCap: number
- readonly outputCap: number
- readonly flag: boolean
-}
-
-// Each kind's `half` splits evenly into its bays (2 × half / bays is whole),
-// so every window and the chimney sit on whole units.
-export const kinds: Readonly<Record<KindId, Kind>> = {
- source: {
- id: "source", title: "Source", blurb: "makes crates from nothing",
- half: 14, stories: 1, bays: 2, window: 6,
- needs: 0, makes: 1, period: 1.4, inputCap: 0, outputCap: 3, flag: false
- },
- workshop: {
- id: "workshop", title: "Workshop", blurb: "relabels one crate at a time",
- half: 16, stories: 1, bays: 2, window: 8,
- needs: 1, makes: 1, period: 1.2, inputCap: 4, outputCap: 3, flag: false
- },
- plant: {
- id: "plant", title: "Plant", blurb: "two crates in, two out, slowly",
- half: 18, stories: 2, bays: 3, window: 6,
- needs: 2, makes: 2, period: 2.6, inputCap: 6, outputCap: 4, flag: false
- },
- depot: {
- id: "depot", title: "Depot", blurb: "ships crates out of the yard",
- half: 14, stories: 1, bays: 2, window: 6,
- needs: 1, makes: 0, period: 0.45, inputCap: 4, outputCap: 0, flag: true
- }
-}
-
-/** How far a kind's walls stand in from the edge of its footprint, in cells. */
-export const insetOf = (kind: Kind): number => 1.5 - kind.half / 16
-
-export const kindOrder: ReadonlyArray<KindId> = ["source", "workshop", "plant", "depot"]
-
-/** Names handed out in placing order, like packages in a repository. */
-export const names = [
- "tokens", "shared", "ui", "db", "lib", "email", "auth", "payments", "components",
- "routes", "pages", "src", "api", "hooks", "store", "config", "core", "assets", "i18n", "utils"
-] as const
-
-/** Awning (and crate label) colours, handed out in placing order. */
-export const awnings = [0x8a58a8, 0x3d6db5, 0x6e8f36, 0xc4523f, 0x2f8c87, 0xd6ae2e, 0x5a6479, 0xd27a34] as const
-
-export const nameFor = (index: number): string => {
- const base = names[index % names.length] ?? "pkg"
- const round = Math.floor(index / names.length)
- return round === 0 ? base : `${base}-${round + 1}`
-}
-
-export const awningFor = (index: number): number => awnings[index % awnings.length] ?? 0x5a6479
diff --git a/src/main.ts b/src/main.ts
index 85c01db..65c576f 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -1,42 +1,98 @@
/**
- * An isometric yard of line-drawn factories joined by conveyor belts, on
- * the bevy-ts ECS with Pixi drawing it.
+ * A town simulation of line-drawn buildings, homes, roads, and land, on the
+ * bevy-ts ECS with Pixi drawing it. The simulation runs on a fixed step;
+ * the views follow once a frame.
*/
+import { FixedLoop } from "@typeonce/bevy-ts-browser"
import { PixiNodeRegistry } from "@typeonce/bevy-ts-pixi"
-import type { BeltView, CrateView, FactoryView } from "./art.ts"
-import { createHost } from "./host.ts"
-import { BeltNodes, Clock, CrateNodes, FactoryNodes, Game, StageService, Ui } from "./schema.ts"
-import { setup, update } from "./systems.ts"
+import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./art.ts"
+import { amounts, STEP_SECONDS } from "./content.ts"
+import { createHost, type Persistence } from "./host.ts"
+import { present } from "./present.ts"
+import { BuildingNodes, Clock, FieldNodes, Game, HouseNodes, RockNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"
+import { simulate } from "./sim/index.ts"
+
+const SAVE_KEY = "town/save"
const start = async () => {
const mount = document.getElementById("app")!
- const { app, stage, ui, syncPage } = await createHost(mount)
- const clock = { deltaSeconds: 1 / 60 }
+ let persistence: Persistence = { save: () => "Not ready", load: () => "Not ready" }
+ const { app, stage, ui, syncPage } = await createHost(mount, () => persistence)
+ const clock = { deltaSeconds: STEP_SECONDS, elapsed: 0 }
- const runtime = Game.Runtime.make({
+ const made = Game.Runtime.make({
services: Game.Runtime.services(
Game.Runtime.service(Ui, ui),
Game.Runtime.service(Clock, clock),
Game.Runtime.service(StageService, stage),
- Game.Runtime.service(FactoryNodes, PixiNodeRegistry.make<FactoryView>(stage.objects)),
- Game.Runtime.service(BeltNodes, PixiNodeRegistry.make<BeltView>(stage.belts)),
- Game.Runtime.service(CrateNodes, PixiNodeRegistry.make<CrateView>(stage.objects))
+ Game.Runtime.service(BuildingNodes, PixiNodeRegistry.make<BuildingView>(stage.objects)),
+ Game.Runtime.service(HouseNodes, PixiNodeRegistry.make<HouseView>(stage.objects)),
+ Game.Runtime.service(WalkerNodes, PixiNodeRegistry.make<WalkerView>(stage.objects)),
+ Game.Runtime.service(TreeNodes, PixiNodeRegistry.make<TreeView>(stage.objects)),
+ Game.Runtime.service(RockNodes, PixiNodeRegistry.make<RockView>(stage.objects)),
+ Game.Runtime.service(FieldNodes, PixiNodeRegistry.make<FieldView>(stage.plates))
),
resources: {
- DeltaTime: 0,
- Elapsed: 0,
- Counters: { nextId: 1, placed: 0 },
- Totals: { shipped: 0 },
- Flow: {}
+ Time: { tick: 0 },
+ Rng: 0x5eed,
+ Treasury: { coins: 0 },
+ Ledger: { taxes: 0, trade: 0, upkeep: 0 },
+ Census: { homes: 0, settlers: 0, citizens: 0, jobs: 0, employed: 0, food: 0, bread: 0, cloth: 0, faith: 0 },
+ Policy: { settlers: 100, citizens: 100, sells: [], reserve: 25 },
+ Grid: { owner: [], use: [] },
+ Stock: amounts({})
}
})
- runtime.tick(setup)
- app.ticker.add((ticker) => {
- clock.deltaSeconds = Math.min(ticker.deltaMS / 1000, 0.05)
- runtime.tick(update)
- syncPage()
+ if (!made.ok) {
+ mount.textContent = `The town could not start: ${JSON.stringify(made.error)}`
+ return
+ }
+ const runtime = made.value
+ // In development, the page's console can reach the town: `town.ui.edits.push(...)`,
+ // `town.runtime.snapshot()`, and `town.advance(seconds)` to fast-forward the simulation.
+ if (import.meta.env.DEV) {
+ const advance = (seconds: number) => {
+ for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)
+ }
+ Object.assign(window, { town: { ui, runtime, advance } })
+ }
+
+ // Saves are plain data; loading validates every component before touching the world.
+ persistence = {
+ save: () => {
+ localStorage.setItem(SAVE_KEY, JSON.stringify(runtime.snapshot()))
+ return null
+ },
+ load: () => {
+ const raw = localStorage.getItem(SAVE_KEY)
+ if (raw === null) return "Nothing saved yet"
+ const restored = runtime.restore(JSON.parse(raw))
+ return restored.ok ? null : `Could not load: ${restored.error._tag}`
+ }
+ }
+
+ const loop = FixedLoop.start({
+ source: FixedLoop.source((onTick) => {
+ const tick = (ticker: { readonly deltaMS: number }) => onTick(ticker)
+ app.ticker.add(tick)
+ return { stop: () => app.ticker.remove(tick) }
+ }),
+ stepSeconds: STEP_SECONDS,
+ maxFrameSeconds: 0.25,
+ maxStepsPerFrame: 8,
+ update: () => runtime.tick(simulate),
+ render: ({ elapsedSeconds }) => {
+ clock.deltaSeconds = elapsedSeconds
+ clock.elapsed += elapsedSeconds
+ runtime.tick(present)
+ syncPage()
+ },
+ onFailure: (failure) => {
+ mount.textContent = failure.kind === "InvalidTickDelta" ? `Invalid frame delta: ${failure.deltaMS}` : "The town stopped after a system failure."
+ }
})
+ if (!loop.ok) mount.textContent = `Invalid fixed-loop option: ${loop.error.field}`
}
void start()
diff --git a/src/mapgen.ts b/src/mapgen.ts
new file mode 100644
index 0000000..a7f3e56
--- /dev/null
+++ b/src/mapgen.ts
@@ -0,0 +1,114 @@
+/**
+ * A new town's land, from a seed: a lake by one edge, a few forests and
+ * single trees, outcrops of stone and a deposit of ore, and a clearing in
+ * the middle where the town hall stands, ringed by a road with a stub
+ * out from each side.
+ * Pure: the same seed always makes the same land.
+ */
+import * as Random from "@typeonce/bevy-ts-math/Random"
+
+import { GROWN } from "./content.ts"
+import { key } from "./grid.ts"
+import { GRID, inside, type Point } from "./iso.ts"
+
+export interface Land {
+ readonly hall: Point
+ readonly roads: ReadonlyArray<Point>
+ readonly water: ReadonlyArray<Point>
+ readonly trees: ReadonlyArray<{ readonly cell: Point; readonly growth: number }>
+ readonly rocks: ReadonlyArray<{ readonly cell: Point; readonly ore: boolean }>
+}
+
+export const generate = (seed: number): Land => {
+ const random = Random.make(seed)
+ const taken = new Set<number>()
+ const centre = { x: GRID / 2, y: GRID / 2 }
+ const hall = { x: centre.x - 2, y: centre.y - 2 }
+ const clearing = 7
+ const near = (c: Point, r: number) => Math.hypot(c.x + 0.5 - centre.x, c.y + 0.5 - centre.y) < r
+ const free = (c: Point) => inside(c.x, c.y) && !taken.has(key(c.x, c.y)) && !near(c, clearing)
+ const take = (c: Point) => taken.add(key(c.x, c.y))
+
+ // The town hall, a ring road around it, and a stub out from the middle of each side.
+ for (let dx = 0; dx < 3; dx++) for (let dy = 0; dy < 3; dy++) take({ x: hall.x + dx, y: hall.y + dy })
+ const roads: Array<Point> = []
+ for (let x = hall.x - 1; x <= hall.x + 3; x++) {
+ for (let y = hall.y - 1; y <= hall.y + 3; y++) {
+ if (x === hall.x - 1 || x === hall.x + 3 || y === hall.y - 1 || y === hall.y + 3) roads.push({ x, y })
+ }
+ }
+ for (let i = 2; i <= 3; i++) {
+ roads.push({ x: hall.x + 2 + i, y: hall.y + 1 }, { x: hall.x + 1, y: hall.y + 2 + i }, { x: hall.x - i, y: hall.y + 1 }, { x: hall.x + 1, y: hall.y - i })
+ }
+ roads.forEach(take)
+
+ // A lake against one edge.
+ const water: Array<Point> = []
+ const side = random.integer(0, 4)
+ const along = random.integer(6, GRID - 6)
+ const lake = [
+ { x: GRID - 2, y: along },
+ { x: along, y: GRID - 2 },
+ { x: 1, y: along },
+ { x: along, y: 1 }
+ ][side]!
+ const rx = random.integer(4, 7)
+ const ry = random.integer(3, 6)
+ for (let y = 0; y < GRID; y++) {
+ for (let x = 0; x < GRID; x++) {
+ const d = ((x - lake.x) / rx) ** 2 + ((y - lake.y) / ry) ** 2
+ const c = { x, y }
+ if (d < 1 + random.range(-0.2, 0.2) && free(c)) {
+ water.push(c)
+ take(c)
+ }
+ }
+ }
+
+ // Forests, then trees on their own.
+ const trees: Array<{ cell: Point; growth: number }> = []
+ const plant = (c: Point) => {
+ if (!free(c)) return
+ trees.push({ cell: c, growth: random.next() < 0.8 ? GROWN.tree : random.integer(0, GROWN.tree) })
+ take(c)
+ }
+ for (let f = 0; f < 6; f++) {
+ let at = { x: random.integer(2, GRID - 2), y: random.integer(2, GRID - 2) }
+ for (let tries = 0; tries < 20 && near(at, clearing + 3); tries++) at = { x: random.integer(2, GRID - 2), y: random.integer(2, GRID - 2) }
+ const count = random.integer(18, 30)
+ let placed = 0
+ for (let tries = 0; placed < count && tries < count * 4; tries++) {
+ const spread = Math.sqrt(random.next()) * 4
+ const turn = random.range(0, Math.PI * 2)
+ const c = { x: Math.round(at.x + Math.cos(turn) * spread), y: Math.round(at.y + Math.sin(turn) * spread) }
+ if (!free(c)) continue
+ plant(c)
+ placed += 1
+ }
+ }
+ for (let i = 0; i < 24; i++) plant({ x: random.integer(0, GRID), y: random.integer(0, GRID) })
+
+ // Outcrops of stone, and a deposit of ore.
+ const rocks: Array<{ cell: Point; ore: boolean }> = []
+ const outcrop = (ore: boolean) => {
+ for (let tries = 0; tries < 20; tries++) {
+ const at = { x: random.integer(2, GRID - 2), y: random.integer(2, GRID - 2) }
+ if (!free(at) || near(at, clearing + 1)) continue
+ const count = random.integer(3, 6)
+ for (let i = 0; i < count; i++) {
+ const c = { x: at.x + random.integer(-1, 2), y: at.y + random.integer(-1, 2) }
+ if (!free(c)) continue
+ rocks.push({ cell: c, ore })
+ take(c)
+ }
+ return
+ }
+ }
+ outcrop(false)
+ outcrop(false)
+ outcrop(false)
+ outcrop(true)
+ outcrop(true)
+
+ return { hall, roads, water, trees, rocks }
+}
diff --git a/src/present.ts b/src/present.ts
new file mode 100644
index 0000000..f986132
--- /dev/null
+++ b/src/present.ts
@@ -0,0 +1,520 @@
+/**
+ * What runs once a frame, after the simulation's steps: the pointer's
+ * gestures become a selection, a preview, and edits for the next step; the
+ * panel, tooltip, and top bar are filled in; and the views follow the world.
+ */
+import { RenderSync } from "@typeonce/bevy-ts-render"
+
+import {
+ BuildingView, drawGhost, drawPlot, drawRoads, drawWater, FieldView, homeHeight, HouseView, RockView, topOf, TreeView, WalkerView,
+ type Doors, type Emphasis
+} from "./art.ts"
+import { BUILD_TICKS, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"
+import { around, canPlace, entrances, isRoad, key, lPath, useAt, type TileLike } from "./grid.ts"
+import { inside, TILE_H, TILE_W, toGrid, toScreen, U, type Point } from "./iso.ts"
+import {
+ Building, BuildingNodes, Census, Clock, Errand, Field, FieldNodes, Figure, Game, Grid, House, HouseNodes, Inventory,
+ Ledger, Policy, Recipe, Rising, Road, Roam, Rock, RockNodes, Route, Service, Site, Staff, StageService, Status, Stock, Tile,
+ TownHall, Treasury, Tree, TreeNodes, Ui, WalkerNodes, WalkerOf, Water, maybe, type GridValue, type Status as StatusValue
+} from "./schema.ts"
+import { capacity, CELL_STEPS, met, SITE_SHARE, taxOf } from "./sim/index.ts"
+import { emptyPreview, type HitBox } from "./ui.ts"
+
+const cellAt = (at: Point): Point => {
+ const g = toGrid(at.x, at.y)
+ return { x: Math.floor(g.x), y: Math.floor(g.y) }
+}
+
+/** The footprint `size` cells a side centred on a point, by its top cell. */
+const footprintAt = (at: Point, size: number): Point => {
+ const g = toGrid(at.x, at.y)
+ return { x: Math.floor(g.x - (size - 1) / 2), y: Math.floor(g.y - (size - 1) / 2) }
+}
+
+/** A thing's hit area: its footprint on the floor, or its body as drawn. */
+const hitBox = (id: number, tile: TileLike, half: number, height: number): HitBox => {
+ const centre = toScreen(tile.x + tile.size / 2, tile.y + tile.size / 2)
+ const a = half * U
+ const top = centre.y - a * TILE_H - height
+ return {
+ id,
+ depth: tile.x + tile.y + tile.size,
+ contains: (at) => {
+ const g = toGrid(at.x, at.y)
+ if (g.x >= tile.x && g.x <= tile.x + tile.size && g.y >= tile.y && g.y <= tile.y + tile.size) return true
+ return Math.abs(at.x - centre.x) <= a * TILE_W && at.y >= top && at.y <= centre.y
+ }
+ }
+}
+
+const hitAt = (hits: ReadonlyArray<HitBox>, at: Point): number | null => hits.find((h) => h.contains(at))?.id ?? null
+
+/** The walls facing the viewer a road meets: the +x side's entrances and the +y side's. */
+const doorsOf = (grid: GridValue, tile: TileLike): Doors => {
+ const open = entrances(tile).filter((c) => isRoad(grid, c.x, c.y))
+ return { right: open.some((c) => c.side === 0), left: open.some((c) => c.side === 1) }
+}
+
+/** How far a kind's work reaches, if it works the land around it. */
+const reachOf = (kind: Kind): number | null => kind.gathers?.radius ?? kind.plants?.radius ?? null
+
+const sourceTitle = { tree: "grown trees", stone: "stone", ore: "ore", field: "ripe fields", water: "water" } as const
+
+/** Why a building is not working, in a line, or `null` when it is fine. */
+const problemOf = (kind: Kind, status: StatusValue, growing = false): string | null => {
+ switch (status) {
+ case "unconnected":
+ return "needs a road at the middle of one of its sides"
+ case "unstaffed":
+ return "no workers: the town needs more residents"
+ case "blocked":
+ return "full: nowhere to take what it makes"
+ case "starved":
+ if (kind.gathers && growing) return `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing`
+ if (kind.gathers) return `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells${kind.gathers.source === "tree" ? ": a forester nearby replants" : ""}`
+ if (kind.recipe?.input) return `waiting for ${kind.recipe.input}`
+ if (kind.service?.service === "goods") return "nothing to hand out: no fish, bread, or cloth here"
+ return "waiting"
+ default:
+ return null
+ }
+}
+
+/** A tree or field gatherer has young ones within reach: it is waiting on them to grow, not on a forester. */
+const growingNear = (grid: GridValue, tile: TileLike, kind: Kind): boolean => {
+ const g = kind.gathers
+ if (!g || (g.source !== "tree" && g.source !== "field")) return false
+ return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === g.source)
+}
+
+const BuildingRead = Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ building: Game.Query.read(Building),
+ status: Game.Query.read(Status),
+ staff: Game.Query.read(Staff),
+ site: Game.Query.optional(Site),
+ rising: Game.Query.optional(Rising),
+ recipe: Game.Query.optional(Recipe),
+ inventory: Game.Query.optional(Inventory),
+ service: Game.Query.optional(Service),
+ walkers: Game.Query.optionalRelated(WalkerOf),
+ hall: Game.Query.optional(TownHall)
+ }
+})
+const HouseRead = Game.Query({
+ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House), site: Game.Query.optional(Site), rising: Game.Query.optional(Rising) }
+})
+
+/** How far up a building or home is: a site rises to its frame as materials come in, then the rest of the way. */
+const buildOf = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined, rising: { readonly ticks: number } | undefined) =>
+ site ? PLATE_SHARE + (SITE_SHARE - PLATE_SHARE) * delivered(site) : rising ? rising.ticks / BUILD_TICKS : 1
+
+const siteShare = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined) => (site ? delivered(site) : null)
+
+/** A site's plate is marked out the moment it is placed. */
+const PLATE_SHARE = 0.12
+/** The share of a site's materials that has arrived. */
+const delivered = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number }) => 1 - total(site.owed) / Math.max(1, site.total)
+
+export const Interact = Game.System(
+ "Town/Interact",
+ {
+ queries: { buildings: BuildingRead, houses: HouseRead },
+ resources: {
+ grid: Game.System.readResource(Grid),
+ census: Game.System.readResource(Census),
+ treasury: Game.System.readResource(Treasury),
+ ledger: Game.System.readResource(Ledger),
+ stock: Game.System.readResource(Stock),
+ policy: Game.System.readResource(Policy)
+ },
+ services: { ui: Game.System.service(Ui) }
+ },
+ ({ queries, resources, services }) => {
+ const ui = services.ui
+ const grid = resources.grid.get()
+ const rates = resources.policy.get()
+ const buildings = queries.buildings.each()
+ const houses = queries.houses.each()
+
+ const hits: Array<HitBox> = [
+ ...buildings.map(({ entity, data }) => {
+ const kind = kinds[data.building.get().kind]
+ return hitBox(entity.id, data.tile.get(), kind.half, topOf(kind))
+ }),
+ ...houses.map(({ entity, data }) => hitBox(entity.id, data.tile.get(), home.half, homeHeight(data.house.get().tier)))
+ ].sort((l, r) => r.depth - l.depth)
+ ui.hits = hits
+ const tileOf = (id: number) => [...buildings, ...houses].find((row) => row.entity.id === id)?.data.tile.get()
+
+ // ── Gestures ──
+ for (const gesture of ui.gestures.splice(0)) {
+ const cell = cellAt(gesture.at)
+ if (gesture.type === "press") {
+ ui.dragFrom = (ui.tool === "road" || ui.tool === "home") && inside(cell.x, cell.y) ? cell : null
+ continue
+ }
+ switch (ui.tool) {
+ case "road":
+ case "home": {
+ if (ui.dragFrom) {
+ const cells = lPath(ui.dragFrom, cell).filter((c) => inside(c.x, c.y))
+ ui.edits.push(ui.tool === "road" ? { type: "roads", cells } : { type: "homes", cells })
+ }
+ ui.dragFrom = null
+ break
+ }
+ case "place": {
+ if (gesture.panned || !ui.placing) break
+ ui.edits.push({ type: "building", kind: ui.placing, cell: footprintAt(gesture.at, kinds[ui.placing].size), open: false })
+ break
+ }
+ case "bulldoze": {
+ if (gesture.panned) break
+ const hit = hitAt(hits, gesture.at)
+ ui.edits.push({ type: "remove", cell: (hit !== null ? tileOf(hit) : undefined) ?? cell })
+ break
+ }
+ case "select": {
+ if (gesture.panned) break
+ ui.selected = hitAt(hits, gesture.at)
+ if (ui.selected !== null) ui.menu = null
+ break
+ }
+ }
+ }
+ if (ui.selected !== null && tileOf(ui.selected) === undefined) ui.selected = null
+
+ // ── Preview ──
+ const preview = emptyPreview()
+ const pointer = ui.pointer
+ const cell = pointer ? cellAt(pointer) : null
+ preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze") ? hitAt(hits, pointer) : null
+ const showReach = (tile: TileLike, kind: Kind) => {
+ const r = reachOf(kind)
+ if (r !== null) preview.plots.push({ x: tile.x - r, y: tile.y - r, size: tile.size + 2 * r, look: "reach" })
+ }
+
+ if (ui.tool === "road" || ui.tool === "home") {
+ const cells = cell === null ? [] : ui.dragFrom ? lPath(ui.dragFrom, cell) : [cell]
+ for (const c of cells) {
+ if (!inside(c.x, c.y)) continue
+ const free = canPlace(grid, { ...c, size: 1 })
+ if (ui.tool === "road") {
+ if (free) preview.roads.push(c)
+ else if (useAt(grid, c.x, c.y) !== "road") preview.plots.push({ ...c, size: 1, look: "blocked" })
+ } else if (free) preview.ghosts.push({ what: "home", cell: c })
+ else preview.plots.push({ ...c, size: 1, look: "blocked" })
+ }
+ } else if (ui.tool === "place" && ui.placing && pointer) {
+ const kind = kinds[ui.placing]
+ const at = footprintAt(pointer, kind.size)
+ const tile = { ...at, size: kind.size }
+ showReach(tile, kind)
+ if (canPlace(grid, tile)) preview.ghosts.push({ what: ui.placing, cell: at })
+ else preview.plots.push({ ...tile, look: "blocked" })
+ } else if (ui.tool === "bulldoze") {
+ preview.danger = true
+ if (preview.hover === null && cell && ["road", "tree", "field"].includes(useAt(grid, cell.x, cell.y))) preview.plots.push({ ...cell, size: 1, look: "blocked" })
+ }
+ if (ui.selected !== null) {
+ const row = buildings.find((b) => b.entity.id === ui.selected)
+ const tile = tileOf(ui.selected)
+ if (tile) preview.plots.push({ ...tile, look: "picked" })
+ if (row && tile) showReach(tile, kinds[row.data.building.get().kind])
+ }
+
+ // ── Tooltip and panel ──
+ const describeBuilding = (row: (typeof buildings)[number]) => {
+ const kind = kinds[row.data.building.get().kind]
+ const status = row.data.status.get()
+ const site = maybe(row.data.site)
+ const lines: Array<string> = []
+ if (site) {
+ const owed = Object.entries(site.owed).filter(([, n]) => n > 0).map(([g, n]) => `${n} ${g}`)
+ lines.push(owed.length > 0 ? `waiting for ${owed.join(", ")}` : "going up")
+ return { kind, status, problem: null, lines }
+ }
+ const staff = row.data.staff.get()
+ if (staff.needed > 0) lines.push(`workers ${staff.assigned} of ${staff.needed}`)
+ const recipe = maybe(row.data.recipe)
+ const inventory = maybe(row.data.inventory)
+ if (recipe) lines.push(`${recipe.input ? `${recipe.inputs} ${recipe.input} → ` : ""}${recipe.batch} ${goods[recipe.output].title} · ${recipe.made} made`)
+ if (inventory && !maybe(row.data.hall)) {
+ const held = inventory.accepts.filter((g) => inventory.stock[g] > 0).map((g) => `${inventory.stock[g]} ${g}`)
+ lines.push(held.length > 0 ? `holds ${held.join(", ")}` : "holds nothing yet")
+ }
+ const walkers = maybe(row.data.walkers)?.length ?? 0
+ if (walkers > 0) lines.push(`${walkers} out on the roads`)
+ if (kind.upkeep > 0) lines.push(`upkeep ${kind.upkeep} coins a minute`)
+ return { kind, status, problem: problemOf(kind, status, status === "starved" && growingNear(grid, row.data.tile.get(), kind)), lines }
+ }
+ const describeHouse = (row: (typeof houses)[number]) => {
+ const h = row.data.house.get()
+ const site = maybe(row.data.site)
+ if (site) return { h, lines: ["waiting for its planks"] }
+ const tier = home.tiers[h.tier]
+ const next = h.tier === 1 ? home.tiers[2] : null
+ const mark = (n: Parameters<typeof met>[1]) => `${needTitle[n]} ${met(h, n) ? "✓" : "–"}`
+ return {
+ h,
+ lines: [
+ `${h.residents} of ${capacity(h, rates)} residents (${tier.residents} at most)`,
+ `needs: ${tier.needs.map(mark).join(" · ")}`,
+ ...(next ? [`to become citizens: ${next.needs.map(mark).join(" · ")}`] : []),
+ `pays ${Math.round(taxOf(h, rates))} coins a minute`
+ ]
+ }
+ }
+
+ const hovered = preview.hover
+ const hoveredBuilding = hovered !== null ? buildings.find((row) => row.entity.id === hovered) : undefined
+ const hoveredHouse = hovered !== null ? houses.find((row) => row.entity.id === hovered) : undefined
+ if (hoveredBuilding) {
+ const { kind, status, problem } = describeBuilding(hoveredBuilding)
+ preview.tooltip = `${kind.title.toLowerCase()} · ${problem ?? status}`
+ } else if (hoveredHouse) {
+ const h = hoveredHouse.data.house.get()
+ preview.tooltip = `${home.tiers[h.tier].title}' home · ${h.residents} residents`
+ } else if (ui.tool === "place" && ui.placing) {
+ const kind = kinds[ui.placing]
+ const r = reachOf(kind)
+ preview.tooltip = `${kind.title.toLowerCase()}${r !== null ? ` · works ${r} cells around` : ""}`
+ }
+ ui.preview = preview
+
+ const pickedBuilding = ui.selected !== null ? buildings.find((row) => row.entity.id === ui.selected) : undefined
+ const pickedHouse = ui.selected !== null ? houses.find((row) => row.entity.id === ui.selected) : undefined
+ if (pickedBuilding) {
+ const { kind, status, problem, lines } = describeBuilding(pickedBuilding)
+ ui.panel = { type: "building", id: pickedBuilding.entity.id, cell: pickedBuilding.data.tile.get(), kind: kind.id, status, problem, lines }
+ } else if (pickedHouse) {
+ const { h, lines } = describeHouse(pickedHouse)
+ ui.panel = { type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines }
+ } else ui.panel = ui.menu ? { type: ui.menu } : null
+
+ const centres = new Map<number, Point>()
+ for (const { entity, data } of [...buildings, ...houses]) {
+ const t = data.tile.get()
+ centres.set(entity.id, toScreen(t.x + t.size / 2, t.y + t.size / 2))
+ }
+ ui.centres = centres
+
+ const census = resources.census.get()
+ const ledger = resources.ledger.get()
+ ui.stats = {
+ coins: resources.treasury.get().coins,
+ taxes: ledger.taxes,
+ trade: ledger.trade,
+ upkeep: ledger.upkeep,
+ net: ledger.taxes + ledger.trade - ledger.upkeep,
+ homes: census.homes,
+ needs: { food: census.food, bread: census.bread, cloth: census.cloth, faith: census.faith },
+ policy: rates,
+ stock: resources.stock.get(),
+ settlers: census.settlers,
+ citizens: census.citizens,
+ jobs: census.jobs,
+ employed: census.employed
+ }
+ }
+)
+
+// ── Views ─────────────────────────────────────────────────────────────────
+
+export const RenderBuildings = RenderSync.system(Game, {
+ name: "Town/RenderBuildings",
+ renderable: Building,
+ transform: Tile,
+ registry: BuildingNodes,
+ services: { stage: StageService },
+ create: ({ renderable, services }) => new BuildingView(renderable.kind, services.stage),
+ apply: (node, { transform }) => node.place(transform.x, transform.y)
+})
+
+export const RenderHouses = RenderSync.system(Game, {
+ name: "Town/RenderHouses",
+ renderable: House,
+ transform: Tile,
+ registry: HouseNodes,
+ services: { stage: StageService },
+ create: ({ services }) => new HouseView(services.stage),
+ apply: (node, { transform }) => node.place(transform.x, transform.y)
+})
+
+export const RenderWalkers = RenderSync.system(Game, {
+ name: "Town/RenderWalkers",
+ renderable: Figure,
+ registry: WalkerNodes,
+ create: ({ renderable }) => new WalkerView(renderable.role, renderable.color),
+ apply: () => {}
+})
+
+export const RenderTrees = RenderSync.system(Game, {
+ name: "Town/RenderTrees",
+ renderable: Tree,
+ transform: Tile,
+ registry: TreeNodes,
+ create: () => new TreeView(),
+ apply: (node, { transform }) => node.place(transform.x, transform.y)
+})
+
+export const RenderRocks = RenderSync.system(Game, {
+ name: "Town/RenderRocks",
+ renderable: Rock,
+ transform: Tile,
+ registry: RockNodes,
+ create: () => new RockView(),
+ apply: (node, { transform }) => node.place(transform.x, transform.y)
+})
+
+export const RenderFields = RenderSync.system(Game, {
+ name: "Town/RenderFields",
+ renderable: Field,
+ transform: Tile,
+ registry: FieldNodes,
+ create: () => new FieldView(),
+ apply: (node, { transform }) => node.place(transform.x, transform.y)
+})
+
+/** Roads and water, each redrawn as one layer whenever one is laid or anything is removed. */
+export const DrawGround = Game.System(
+ "Town/DrawGround",
+ {
+ queries: {
+ roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),
+ water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),
+ laid: Game.Query({ selection: { tile: Game.Query.read(Tile) }, filters: [Game.Query.added(Tile)] })
+ },
+ despawned: { entities: Game.System.readDespawned() },
+ services: { stage: Game.System.service(StageService) }
+ },
+ ({ queries, despawned, services }) => {
+ if (queries.laid.each().length === 0 && despawned.entities.all().length === 0) return
+ const cellsOf = (rows: ReadonlyArray<{ readonly data: { readonly tile: { get(): TileLike } } }>) =>
+ new Set(rows.map(({ data }) => key(data.tile.get().x, data.tile.get().y)))
+ services.stage.roads.clear()
+ drawRoads(services.stage.roads, cellsOf(queries.roads.each()))
+ services.stage.ground.clear()
+ drawWater(services.stage.ground, cellsOf(queries.water.each()))
+ }
+)
+
+/**
+ * Where a walker stands, in cells: on the lattice, a little to one side of
+ * the road's middle; which way it faces; and which foot is forward.
+ */
+const walkerAt = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number; readonly step: number }) => {
+ const here = route.cells[route.index]!
+ const next = route.cells[route.index + 1]
+ const before = route.cells[route.index - 1]
+ const dir = next ? { x: next.x - here.x, y: next.y - here.y } : before ? { x: here.x - before.x, y: here.y - before.y } : { x: 0, y: 0 }
+ const units = next ? Math.floor(route.step / (CELL_STEPS / 16)) : 0
+ const along = units * U
+ const side = 2 * U
+ return {
+ x: here.x + 0.5 + dir.x * along - dir.y * side,
+ y: here.y + 0.5 + dir.y * along + dir.x * side,
+ dir,
+ phase: next ? Math.floor(units / 3) % 2 : 0
+ }
+}
+
+export const Animate = Game.System(
+ "Town/Animate",
+ {
+ queries: {
+ buildings: BuildingRead,
+ houses: HouseRead,
+ walkers: Game.Query({ selection: { route: Game.Query.read(Route), errand: Game.Query.optional(Errand), roam: Game.Query.optional(Roam) } }),
+ trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),
+ rocks: Game.Query({ selection: { rock: Game.Query.read(Rock) } }),
+ fields: Game.Query({ selection: { field: Game.Query.read(Field) } })
+ },
+ resources: { grid: Game.System.readResource(Grid) },
+ services: {
+ ui: Game.System.service(Ui),
+ clock: Game.System.service(Clock),
+ buildingNodes: Game.System.service(BuildingNodes),
+ houseNodes: Game.System.service(HouseNodes),
+ walkerNodes: Game.System.service(WalkerNodes),
+ treeNodes: Game.System.service(TreeNodes),
+ rockNodes: Game.System.service(RockNodes),
+ fieldNodes: Game.System.service(FieldNodes)
+ }
+ },
+ ({ queries, resources, services }) => {
+ const grid = resources.grid.get()
+ const { hover, danger } = services.ui.preview
+ const emphasis = (id: number): Emphasis => (danger && hover === id ? "danger" : "normal")
+ const dt = services.clock.deltaSeconds
+
+ for (const { entity, data } of queries.buildings.each()) {
+ const kind = kinds[data.building.get().kind]
+ const status = data.status.get()
+ const recipe = maybe(data.recipe)
+ const walkers = maybe(data.walkers)?.length ?? 0
+ services.buildingNodes.get(entity.id)?.update(
+ {
+ working: status === "working",
+ problem: problemOf(kind, status) !== null,
+ build: buildOf(maybe(data.site), maybe(data.rising)),
+ beat: recipe ? recipe.made : maybe(data.service) ? walkers : 0,
+ doors: doorsOf(grid, data.tile.get()),
+ site: siteShare(maybe(data.site))
+ },
+ dt,
+ emphasis(entity.id)
+ )
+ }
+ for (const { entity, data } of queries.houses.each()) {
+ services.houseNodes.get(entity.id)?.update(
+ { tier: data.house.get().tier, build: buildOf(maybe(data.site), maybe(data.rising)), doors: doorsOf(grid, data.tile.get()), site: siteShare(maybe(data.site)) },
+ emphasis(entity.id)
+ )
+ }
+ for (const { entity, data } of queries.walkers.each()) {
+ const p = walkerAt(data.route.get())
+ const errand = maybe(data.errand)
+ const roam = maybe(data.roam)
+ const cargo = errand ? !errand.back || errand.count > 0 : roam ? total(roam.basket) > 0 : false
+ services.walkerNodes.get(entity.id)?.update(p.x, p.y, p.dir, p.phase, cargo)
+ }
+ for (const { entity, data } of queries.trees.each()) services.treeNodes.get(entity.id)?.update(data.tree.get().growth, emphasis(entity.id))
+ for (const { entity, data } of queries.rocks.each()) {
+ const r = data.rock.get()
+ services.rockNodes.get(entity.id)?.update(r.ore, r.amount)
+ }
+ for (const { entity, data } of queries.fields.each()) services.fieldNodes.get(entity.id)?.update(data.field.get().growth)
+ }
+)
+
+/** Ghosts, the road being dragged, and outlines, redrawn every frame. */
+export const DrawPreview = Game.System(
+ "Town/DrawPreview",
+ { services: { ui: Game.System.service(Ui), stage: Game.System.service(StageService), clock: Game.System.service(Clock) } },
+ ({ services }) => {
+ const { plots, ghosts, roads } = services.ui.preview
+ const { overlay, ghost } = services.stage
+ overlay.clear()
+ ghost.clear()
+ for (const plot of plots) drawPlot(overlay, plot.x, plot.y, plot.size, plot.look, services.clock.elapsed)
+ if (roads.length > 0) drawRoads(overlay, new Set(roads.map((c) => key(c.x, c.y))), 0.6, 0x8f9891)
+ for (const g of ghosts) drawGhost(ghost, g.what, g.cell.x, g.cell.y)
+ ghost.alpha = 0.5
+ }
+)
+
+export const present = Game.Schedule(
+ Interact,
+ RenderBuildings,
+ RenderHouses,
+ RenderWalkers,
+ RenderTrees,
+ RenderRocks,
+ RenderFields,
+ DrawGround,
+ Animate,
+ DrawPreview
+)
diff --git a/src/route.ts b/src/route.ts
deleted file mode 100644
index 26690b1..0000000
--- a/src/route.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * Belt routing on the grid: the cheapest path of cells between two
- * factories, going straight where it can. Belts may cross other belts at a
- * right angle, never run along one, and turn only on a free cell.
- */
-import { FOOTPRINT, GRID, inside, type Point } from "./iso.ts"
-
-/** +x, +y, -x, -y. */
-export type Dir = 0 | 1 | 2 | 3
-const DX = [1, 0, -1, 0] as const
-const DY = [0, 1, 0, -1] as const
-const opposite = (dir: Dir): Dir => ((dir + 2) % 4) as Dir
-const axisOf = (dir: Dir): "h" | "v" => (dir % 2 === 0 ? "h" : "v")
-
-/** What the belts already on a cell use of it. */
-export interface Usage {
- h: boolean
- v: boolean
- turn: boolean
-}
-
-/** A factory's footprint (see `FOOTPRINT`), by its top cell. */
-export interface Footprint {
- readonly x: number
- readonly y: number
-}
-
-export interface Yard {
- /** A factory stands on the cell. */
- readonly blocked: (x: number, y: number) => boolean
- readonly usage: (x: number, y: number) => Usage | undefined
-}
-
-export interface Route {
- /** The cells the belt covers, in order. */
- readonly cells: ReadonlyArray<Point>
- /** How the belt uses each cell (see `Usage`). */
- readonly uses: ReadonlyArray<"h" | "v" | "turn">
- /** The belt's centre line: from the source's wall, through each turn, to the target's wall. */
- readonly points: ReadonlyArray<Point>
-}
-
-export const key = (x: number, y: number): number => y * GRID + x
-
-/**
- * A factory's ports: the cell just outside the middle of each side, with the
- * direction pointing away from it. A belt meets the wall there, on its door.
- */
-export const sideCells = (fp: Footprint): ReadonlyArray<{ readonly x: number; readonly y: number; readonly dir: Dir }> => {
- const mid = (FOOTPRINT - 1) / 2
- return [
- { x: fp.x + FOOTPRINT, y: fp.y + mid, dir: 0 },
- { x: fp.x + mid, y: fp.y + FOOTPRINT, dir: 1 },
- { x: fp.x - 1, y: fp.y + mid, dir: 2 },
- { x: fp.x + mid, y: fp.y - 1, dir: 3 }
- ]
-}
-
-const STEP = 1
-const TURN = 1.6
-const CROSS = 2.5
-
-/** Whether a belt may enter a cell going `into` and leave it going `out`. */
-const fits = (yard: Yard, x: number, y: number, into: Dir, out: Dir): boolean => {
- const usage = yard.usage(x, y)
- if (usage === undefined) return true
- if (into !== out) return false
- return !usage.turn && !usage[axisOf(into)]
-}
-
-/** A binary heap of state indices by cost. */
-class Heap {
- private readonly items: Array<{ cost: number; state: number }> = []
- get size() {
- return this.items.length
- }
- push(cost: number, state: number) {
- const items = this.items
- items.push({ cost, state })
- let i = items.length - 1
- while (i > 0) {
- const parent = (i - 1) >> 1
- if (items[parent]!.cost <= items[i]!.cost) break
- ;[items[parent], items[i]] = [items[i]!, items[parent]!]
- i = parent
- }
- }
- pop() {
- const items = this.items
- const top = items[0]!
- const last = items.pop()!
- if (items.length > 0) {
- items[0] = last
- let i = 0
- for (;;) {
- const l = i * 2 + 1
- const r = l + 1
- let m = i
- if (l < items.length && items[l]!.cost < items[m]!.cost) m = l
- if (r < items.length && items[r]!.cost < items[m]!.cost) m = r
- if (m === i) break
- ;[items[m], items[i]] = [items[i]!, items[m]!]
- i = m
- }
- }
- return top
- }
-}
-
-/**
- * The cheapest belt from `from`'s walls to `to`'s walls, or to the free cell
- * `to` (a belt being dragged), or `null` when there is none.
- */
-export const route = (yard: Yard, from: Footprint, to: Footprint | { readonly cell: Point }): Route | null => {
- const states = GRID * GRID * 4
- const GOAL = states
- const cost = new Float64Array(states + 1).fill(Infinity)
- const previous = new Int32Array(states + 1).fill(-1)
- const heap = new Heap()
- const stateOf = (x: number, y: number, dir: Dir) => key(x, y) * 4 + dir
-
- const free = (x: number, y: number) => inside(x, y) && !yard.blocked(x, y)
-
- // Where the belt may end: a cell beside the target and the direction into it.
- const goals = new Map<number, Dir>()
- if ("cell" in to) {
- if (!free(to.cell.x, to.cell.y)) return null
- } else {
- for (const side of sideCells(to)) if (free(side.x, side.y)) goals.set(key(side.x, side.y), opposite(side.dir))
- }
- const isGoal = (x: number, y: number) => ("cell" in to ? x === to.cell.x && y === to.cell.y : goals.has(key(x, y)))
-
- for (const side of sideCells(from)) {
- if (!free(side.x, side.y)) continue
- const state = stateOf(side.x, side.y, side.dir)
- cost[state] = 0
- heap.push(0, state)
- }
-
- while (heap.size > 0) {
- const { cost: at, state } = heap.pop()
- if (state === GOAL) break
- if (at > cost[state]!) continue
- const into = (state % 4) as Dir
- const cell = Math.floor(state / 4)
- const x = cell % GRID
- const y = Math.floor(cell / GRID)
-
- if (isGoal(x, y)) {
- const out = "cell" in to ? into : goals.get(key(x, y))!
- if (fits(yard, x, y, into, out)) {
- const total = at + (out === into ? 0 : TURN)
- if (total < cost[GOAL]!) {
- cost[GOAL] = total
- previous[GOAL] = state
- heap.push(total, GOAL)
- }
- }
- }
-
- for (const out of [0, 1, 2, 3] as const) {
- if (out === opposite(into)) continue
- if (!fits(yard, x, y, into, out)) continue
- const nx = x + DX[out]
- const ny = y + DY[out]
- if (!free(nx, ny)) continue
- const next = stateOf(nx, ny, out)
- const total = at + STEP + (out === into ? 0 : TURN) + (yard.usage(nx, ny) ? CROSS : 0)
- if (total < cost[next]!) {
- cost[next] = total
- previous[next] = state
- heap.push(total, next)
- }
- }
- }
-
- if (previous[GOAL] === -1) return null
-
- // Walk back from the goal: cells and the direction each was entered by.
- const trail: Array<{ x: number; y: number; dir: Dir }> = []
- for (let state = previous[GOAL]!; state !== -1; state = previous[state]!) {
- const cell = Math.floor(state / 4)
- trail.push({ x: cell % GRID, y: Math.floor(cell / GRID), dir: (state % 4) as Dir })
- }
- trail.reverse()
- const last = trail[trail.length - 1]!
- const exit: Dir = "cell" in to ? last.dir : goals.get(key(last.x, last.y))!
-
- const cells = trail.map(({ x, y }) => ({ x, y }))
- const uses = trail.map((step, i) => {
- const out = i + 1 < trail.length ? trail[i + 1]!.dir : exit
- return step.dir === out ? axisOf(out) : ("turn" as const)
- })
-
- const first = trail[0]!
- const points: Array<Point> = [{ x: first.x + 0.5 - DX[first.dir] * 0.5, y: first.y + 0.5 - DY[first.dir] * 0.5 }]
- trail.forEach((step, i) => {
- if (uses[i] === "turn") points.push({ x: step.x + 0.5, y: step.y + 0.5 })
- })
- points.push(
- "cell" in to
- ? { x: last.x + 0.5, y: last.y + 0.5 }
- : { x: last.x + 0.5 + DX[exit] * 0.5, y: last.y + 0.5 + DY[exit] * 0.5 }
- )
- return { cells, uses, points }
-}
-
-/** A polyline's length and the point at a distance along it. */
-export const lengthOf = (points: ReadonlyArray<Point>): number => {
- let total = 0
- for (let i = 1; i < points.length; i++) total += Math.hypot(points[i]!.x - points[i - 1]!.x, points[i]!.y - points[i - 1]!.y)
- return total
-}
-
-export const pointAt = (points: ReadonlyArray<Point>, distance: number): Point => {
- let left = distance
- for (let i = 1; i < points.length; i++) {
- const a = points[i - 1]!
- const b = points[i]!
- const span = Math.hypot(b.x - a.x, b.y - a.y)
- if (left <= span || i === points.length - 1) {
- const t = span === 0 ? 0 : Math.min(1, Math.max(0, left / span))
- return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }
- }
- left -= span
- }
- return points[0] ?? { x: 0, y: 0 }
-}
diff --git a/src/schema.ts b/src/schema.ts
index b2bd48c..f780962 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -1,173 +1,202 @@
-/** The factory yard's world: what is placed, what it is doing, and what moves. */
-import { Descriptor, Schema } from "@typeonce/bevy-ts"
+/**
+ * The town's world. Every entity is assembled from small components (see
+ * `archetypes.ts`): a `Tile` on the grid, then whichever roles it has. The
+ * land is `Tree`s, `Rock`s, `Water`, and a farm's `Field`s; the town is
+ * `Road`s, `House`s, and `Building`s that may hold an `Inventory`, follow a
+ * `Recipe`, gather from the land (`Gatherer`), plant (`Planter`), send
+ * `Carriers`, or offer a `Service`. A building still owed materials is a
+ * `Site`; one going up is `Rising`. Walkers follow a `Route` on an `Errand`
+ * or a `Roam`, as children of the building that sent them.
+ *
+ * Saved components and resources are constructed with a validator, so the
+ * whole world snapshots to plain data and loads back checked.
+ */
+import { Decode, Descriptor, Schema } from "@typeonce/bevy-ts"
+import type { OptionalReadCell } from "@typeonce/bevy-ts/Query"
import type { NodeRegistry } from "@typeonce/bevy-ts-render"
-import type { Point } from "./iso.ts"
-import type { KindId } from "./kinds.ts"
-import type { BeltView, CrateView, FactoryView, Stage } from "./art.ts"
-
-export type Status = "building" | "idle" | "working" | "starved" | "blocked"
-
-/** A placed factory: its own id (belts refer to it), kind, and 2×2 footprint by its top cell. */
-export interface FactoryValue {
- readonly id: number
- readonly kind: KindId
- readonly name: string
- readonly color: number
- readonly x: number
- readonly y: number
+import type { BuildingView, FieldView, HouseView, RockView, Stage, TreeView, WalkerView } from "./art.ts"
+import { goodIds, kindIds, type Amounts } from "./content.ts"
+import type { UiValue } from "./ui.ts"
+
+export const Root = Schema.defineRoot("Town")
+
+/** An optional query slot's value, or `undefined` when the entity lacks it. */
+export const maybe = <T>(cell: OptionalReadCell<T>) => (cell.present ? cell.get() : undefined)
+
+const integer = Decode.integer
+const cell = Decode.struct({ x: integer, y: integer })
+const good = Decode.literal(...goodIds)
+const service = Decode.literal("goods", "faith")
+/** A count of every good. */
+const amounts = Decode.struct({
+ wood: integer, planks: integer, stone: integer, ore: integer, tools: integer, fish: integer,
+ wheat: integer, flour: integer, bread: integer, wool: integer, cloth: integer
+})
+
+export const statuses = ["building", "idle", "working", "starved", "blocked", "unstaffed", "unconnected"] as const
+export type Status = (typeof statuses)[number]
+
+// ── On the grid ───────────────────────────────────────────────────────────
+
+/** A square of cells on the grid, by its top cell, `size` cells a side. */
+export const Tile = Descriptor.ConstructedComponent(Decode.struct({ x: integer, y: integer, size: integer }))("Town/Tile")
+export const Road = Descriptor.Tag("Town/Road")
+/** Materials still owed before it can go up, out of `total`. */
+export const Site = Descriptor.ConstructedComponent(Decode.struct({ owed: amounts, total: integer }))("Town/Site")
+/** Going up: steps since its materials were all in (see `BUILD_TICKS`). Removed once it stands. */
+export const Rising = Descriptor.ConstructedComponent(Decode.struct({ ticks: integer }))("Town/Rising")
+
+// ── The land ──────────────────────────────────────────────────────────────
+
+export const Tree = Descriptor.ConstructedComponent(Decode.struct({ growth: integer }))("Town/Tree")
+export const Rock = Descriptor.ConstructedComponent(Decode.struct({ ore: Decode.boolean, amount: integer }))("Town/Rock")
+export const Water = Descriptor.Tag("Town/Water")
+export const Field = Descriptor.ConstructedComponent(Decode.struct({ growth: integer }))("Town/Field")
+
+// ── Homes ─────────────────────────────────────────────────────────────────
+
+/** A home: its tier, residents, and steps left of each need a walker last met. */
+export const House = Descriptor.ConstructedComponent(Decode.struct({
+ tier: Decode.literal(1, 2),
+ residents: integer,
+ food: integer,
+ bread: integer,
+ cloth: integer,
+ faith: integer,
+ clock: integer
+}))("Town/House")
+
+// ── Buildings and their roles ─────────────────────────────────────────────
+
+export const Building = Descriptor.ConstructedComponent(Decode.struct({ kind: Decode.literal(...kindIds) }))("Town/Building")
+export const TownHall = Descriptor.Tag("Town/TownHall")
+export const Status = Descriptor.ConstructedComponent(Decode.literal(...statuses))("Town/Status")
+
+/** Workers it needs, and how many the town could spare it this step. */
+export const Staff = Descriptor.ConstructedComponent(Decode.struct({ needed: integer, assigned: integer }))("Town/Staff")
+
+/** Goods on hand: only the ones it `accepts`, up to `cap` of each. */
+export const Inventory = Descriptor.ConstructedComponent(Decode.struct({ stock: amounts, accepts: Decode.array(good), cap: integer }))("Town/Inventory")
+/** Takes any good in, and sends goods out to whoever needs them. */
+export const Storage = Descriptor.Tag("Town/Storage")
+
+/** Turns inputs (or nothing) into outputs: a job takes `period` steps of a full crew. */
+export const Recipe = Descriptor.ConstructedComponent(Decode.struct({
+ input: Decode.nullable(good),
+ inputs: integer,
+ output: good,
+ batch: integer,
+ period: integer,
+ /** Worker-steps put into the current job (0: none started). */
+ progress: integer,
+ made: integer
+}))("Town/Recipe")
+
+/** Its recipe needs this within `radius` cells of its footprint. */
+export const Gatherer = Descriptor.ConstructedComponent(Decode.struct({
+ source: Decode.literal("tree", "stone", "ore", "field", "water"),
+ radius: integer
+}))("Town/Gatherer")
+
+/** Plants trees or fields within `radius`, one every `interval` steps, up to `max`. */
+export const Planter = Descriptor.ConstructedComponent(Decode.struct({
+ what: Decode.literal("tree", "field"),
+ radius: integer,
+ interval: integer,
+ cooldown: integer,
+ max: integer
+}))("Town/Planter")
+
+/** Carriers it may have out at once. */
+export const Carriers = Descriptor.ConstructedComponent(Decode.struct({ count: integer }))("Town/Carriers")
+
+/** Sends a walker out every `interval` steps. */
+export const Service = Descriptor.ConstructedComponent(Decode.struct({ service, interval: integer, cooldown: integer, range: integer }))("Town/Service")
+
+// ── Walkers ───────────────────────────────────────────────────────────────
+
+/** How a walker looks: a carrier, or a walker in its building's colour. */
+export const Figure = Descriptor.ConstructedComponent(Decode.struct({ role: Decode.literal("carrier", "walker"), color: integer }))("Town/Figure")
+
+/**
+ * Where a walker is going: road cells in order, the one it last reached, and
+ * how far on to the next (in steps of `CELL_STEPS`). At the last cell it has
+ * arrived, and waits for its errand or roam to give it somewhere new.
+ */
+export const Route = Descriptor.ConstructedComponent(Decode.struct({ cells: Decode.array(cell), index: integer, step: integer }))("Town/Route")
+
+/** Carrying `count` of a good to a building, then walking back (still carrying it, if it could not be handed over). */
+export const Errand = Descriptor.ConstructedComponent(Decode.struct({
+ target: Decode.handle(Root, Tile),
+ good,
+ count: integer,
+ back: Decode.boolean
+}))("Town/Errand")
+
+/** Wandering the roads serving homes, `left` cells more, then walking back with what is left in its basket. */
+export const Roam = Descriptor.ConstructedComponent(Decode.struct({ service, left: integer, basket: amounts, back: Decode.boolean }))("Town/Roam")
+
+/** A walker belongs to the building that sent it, and goes when it goes. */
+export const { relation: WalkerOf } = Descriptor.Hierarchy("Town/WalkerOf", "Town/Walkers")
+/** A field belongs to the farm that sowed it. */
+export const { relation: FieldOf } = Descriptor.Hierarchy("Town/FieldOf", "Town/Fields")
+
+// ── Resources ─────────────────────────────────────────────────────────────
+
+export const Time = Descriptor.ConstructedResource(Decode.struct({ tick: integer }))("Town/Time")
+/** The deterministic random state (see `@typeonce/bevy-ts-math/Random`). */
+export const Rng = Descriptor.ConstructedResource(integer)("Town/Rng")
+export const Treasury = Descriptor.ConstructedResource(Decode.struct({ coins: integer }))("Town/Treasury")
+/** The last collection's taxes, trade, and upkeep, per minute. */
+export const Ledger = Descriptor.ConstructedResource(Decode.struct({ taxes: integer, trade: integer, upkeep: integer }))("Town/Ledger")
+export const Census = Descriptor.ConstructedResource(Decode.struct({
+ homes: integer,
+ settlers: integer,
+ citizens: integer,
+ jobs: integer,
+ employed: integer,
+ /** Homes with each need met right now. */
+ food: integer,
+ bread: integer,
+ cloth: integer,
+ faith: integer
+}))("Town/Census")
+/** The town's tax rates (in percent of the usual, for each tier), and what it sells to traders beyond the reserve it keeps. */
+export const Policy = Descriptor.ConstructedResource(Decode.struct({ settlers: integer, citizens: integer, sells: Decode.array(good), reserve: integer }))("Town/Policy")
+
+/** What stands on each cell, rebuilt every step from the tiles (see `grid.ts`). */
+export type Use = "empty" | "road" | "house" | "building" | "tree" | "rock" | "water" | "field"
+export interface GridValue {
+ /** Entity id on each cell (by `key`), or 0. */
+ readonly owner: ReadonlyArray<number>
+ readonly use: ReadonlyArray<Use>
}
-
-/** What a factory is doing, and the numbers its animation follows. */
-export interface WorkValue {
- readonly status: Status
- /** 0 → 1 while it rises from its plate. */
- readonly built: number
- /** 0 → 1 through the current job (0: no job). */
- readonly progress: number
- readonly inputs: number
- readonly outputs: number
- /** Crates a depot has shipped out of the yard. */
- readonly shipped: number
- /** Jobs finished. */
- readonly made: number
- /** Next outgoing belt to try. */
- readonly turn: number
- /** 1 when a job finishes, fading to 0: the building's bounce. */
- readonly pulse: number
-}
-
-/** A conveyor between two factories. */
-export interface BeltValue {
- readonly id: number
- readonly from: number
- readonly to: number
- readonly cells: ReadonlyArray<Point>
- readonly uses: ReadonlyArray<"h" | "v" | "turn">
- readonly points: ReadonlyArray<Point>
- readonly length: number
-}
-
-/** A crate riding a belt: how far along it, and where that is on the grid. */
-export interface CrateValue {
- readonly belt: number
- readonly distance: number
- readonly color: number
- readonly x: number
- readonly y: number
-}
-
-export type Mode = "select" | "bulldoze"
-
-/** What the player did since the last tick, in world pixels. */
-export type Intent =
- | { readonly type: "press"; readonly at: Point }
- | { readonly type: "release"; readonly at: Point; readonly panned: boolean }
- | { readonly type: "place"; readonly kind: KindId; readonly cell: Point }
- /** Builds on the picked plot (see `UiValue.plot`), and opens the new factory. */
- | { readonly type: "build"; readonly kind: KindId }
- | { readonly type: "remove"; readonly factory: number }
- /** Connects the factories standing on two cells. */
- | { readonly type: "link"; readonly from: Point; readonly to: Point }
- | { readonly type: "clear" }
-
-/** What the yard shows besides its entities: the ghost, the belt being dragged, and what is in focus. */
-export interface Preview {
- ghost: { readonly kind: KindId; readonly cell: Point; readonly valid: boolean } | null
- /** Plots outlined on the floor: under the pointer, or picked. */
- plots: Array<{ readonly x: number; readonly y: number; readonly look: "hover" | "picked" | "blocked" }>
- path: { readonly points: ReadonlyArray<Point>; readonly valid: boolean } | null
- hoverFactory: number | null
- hoverBelt: number | null
- /** Factories and belts in focus (the rest fade), or `null` for all. */
- focus: { readonly factories: ReadonlySet<number>; readonly belts: ReadonlySet<number> } | null
- danger: boolean
- tooltip: string | null
-}
-
-/** A factory a panel lists, with where it stands (world pixels) to look at it. */
-export interface PanelLink {
- readonly id: number
- readonly name: string
- readonly kind: KindId
- readonly crates: number
-}
-
-/** The side panel: a picked plot and what can be built on it, or a factory and its belts. */
-export type Panel =
- | {
- readonly type: "plot"
- readonly x: number
- readonly y: number
- readonly free: boolean
- readonly reason: string
- }
- | {
- readonly type: "factory"
- readonly id: number
- readonly name: string
- readonly kind: KindId
- readonly status: Status
- readonly inputs: number
- readonly outputs: number
- readonly made: number
- readonly takes: ReadonlyArray<PanelLink>
- readonly feeds: ReadonlyArray<PanelLink>
- readonly linking: boolean
- }
-
-/** A factory's hit area for the pointer, written by the yard each tick. */
-export interface HitBox {
- readonly id: number
- readonly depth: number
- readonly contains: (at: Point) => boolean
-}
-
-/** The bridge between the page and the yard: the host writes input, the yard writes the preview. */
-export interface UiValue {
- mode: Mode
- /** The plot picked for building (its top cell), and the kind the panel is pointing at. */
- plot: Point | null
- plotKind: KindId | null
- /** A factory whose next belt the player is placing by tapping its target. */
- linkFrom: number | null
- /** The pointer in world pixels, or `null` off the canvas. */
- pointer: Point | null
- dragFrom: number | null
- selected: number | null
- intents: Array<Intent>
- preview: Preview
- hits: ReadonlyArray<HitBox>
- panel: Panel | null
- /** Where each factory stands (world pixels), for the camera to look at. */
- centres: ReadonlyMap<number, Point>
- stats: { readonly factories: number; readonly belts: number; readonly crates: number; readonly shipped: number }
- toast: (message: string) => void
-}
-
-export const Factory = Descriptor.Component<FactoryValue>()("Factory/Factory")
-export const Work = Descriptor.Component<WorkValue>()("Factory/Work")
-export const Belt = Descriptor.Component<BeltValue>()("Factory/Belt")
-export const Crate = Descriptor.Component<CrateValue>()("Factory/Crate")
-
-export const DeltaTime = Descriptor.Resource<number>()("Factory/DeltaTime")
-export const Elapsed = Descriptor.Resource<number>()("Factory/Elapsed")
-/** Ids for factories and belts, and how many factories were ever placed (for names and colours). */
-export const Counters = Descriptor.Resource<{ readonly nextId: number; readonly placed: number }>()("Factory/Counters")
-export const Totals = Descriptor.Resource<{ readonly shipped: number }>()("Factory/Totals")
-/** Crates each belt has delivered, by belt id. */
-export const Flow = Descriptor.Resource<Readonly<Record<number, number>>>()("Factory/Flow")
-
-export const Ui = Descriptor.Service<UiValue>()("Factory/Ui")
-export const Clock = Descriptor.Service<{ deltaSeconds: number }>()("Factory/Clock")
-export const StageService = Descriptor.Service<Stage>()("Factory/Stage")
-export const FactoryNodes = Descriptor.Service<NodeRegistry.NodeRegistry<FactoryView>>()("Factory/FactoryNodes")
-export const BeltNodes = Descriptor.Service<NodeRegistry.NodeRegistry<BeltView>>()("Factory/BeltNodes")
-export const CrateNodes = Descriptor.Service<NodeRegistry.NodeRegistry<CrateView>>()("Factory/CrateNodes")
+export const Grid = Descriptor.TransientResource<GridValue>()("Town/Grid")
+/** Goods in the town's storage, summed every step. */
+export const Stock = Descriptor.TransientResource<Amounts>()("Town/Stock")
+
+// ── Host services ─────────────────────────────────────────────────────────
+
+export const Ui = Descriptor.Service<UiValue>()("Town/Ui")
+/** The frame's length, for animation only: the simulation runs on `Time`. */
+export const Clock = Descriptor.Service<{ deltaSeconds: number; elapsed: number }>()("Town/Clock")
+export const StageService = Descriptor.Service<Stage>()("Town/Stage")
+export const BuildingNodes = Descriptor.Service<NodeRegistry.NodeRegistry<BuildingView>>()("Town/BuildingNodes")
+export const HouseNodes = Descriptor.Service<NodeRegistry.NodeRegistry<HouseView>>()("Town/HouseNodes")
+export const WalkerNodes = Descriptor.Service<NodeRegistry.NodeRegistry<WalkerView>>()("Town/WalkerNodes")
+export const TreeNodes = Descriptor.Service<NodeRegistry.NodeRegistry<TreeView>>()("Town/TreeNodes")
+export const RockNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RockView>>()("Town/RockNodes")
+export const FieldNodes = Descriptor.Service<NodeRegistry.NodeRegistry<FieldView>>()("Town/FieldNodes")
export const Game = Schema.bind(
Schema.fragment({
- components: { Factory, Work, Belt, Crate },
- resources: { DeltaTime, Elapsed, Counters, Totals, Flow }
- })
+ components: {
+ Tile, Road, Site, Rising, Tree, Rock, Water, Field, House, Building, TownHall, Status, Staff, Inventory, Storage,
+ Recipe, Gatherer, Planter, Carriers, Service, Figure, Route, Errand, Roam
+ },
+ resources: { Time, Rng, Treasury, Ledger, Census, Policy, Grid, Stock },
+ relations: { WalkerOf, FieldOf }
+ }),
+ Root
)
diff --git a/src/sim/edits.ts b/src/sim/edits.ts
new file mode 100644
index 0000000..a26e25b
--- /dev/null
+++ b/src/sim/edits.ts
@@ -0,0 +1,187 @@
+/**
+ * The player's edits, applied at the start of a step: building, laying
+ * roads and homes, bulldozing, and founding a new town. Costs are checked
+ * against the treasury and the town's stock and paid up front in coins; the
+ * materials are carried to the site afterwards.
+ */
+import {
+ buildingDraft, houseDraft, houseStart, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft
+} from "../archetypes.ts"
+import { amounts, goodIds, home, kinds, ROAD_COST, ROCK_AMOUNT, start, trade, type Amounts, type Kind } from "../content.ts"
+import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"
+import { inside } from "../iso.ts"
+import { generate } from "../mapgen.ts"
+import { Census, Game, Inventory, Ledger, Policy, Rng, Status, Stock, TownHall, Treasury, Ui } from "../schema.ts"
+import { TileRead, useOf } from "./shared.ts"
+
+export const unlocked = (kind: Kind, census: { readonly settlers: number; readonly citizens: number }) =>
+ census.settlers + census.citizens >= kind.unlock.residents && census.citizens >= kind.unlock.citizens
+
+export const ApplyEdits = Game.System(
+ "Town/ApplyEdits",
+ {
+ queries: {
+ tiles: TileRead,
+ halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } })
+ },
+ resources: {
+ treasury: Game.System.writeResource(Treasury),
+ ledger: Game.System.writeResource(Ledger),
+ policy: Game.System.writeResource(Policy),
+ rng: Game.System.writeResource(Rng),
+ stock: Game.System.readResource(Stock),
+ census: Game.System.readResource(Census)
+ },
+ services: { ui: Game.System.service(Ui) }
+ },
+ ({ queries, resources, services, commands }) => {
+ const ui = services.ui
+ if (ui.edits.length === 0) return
+ const grid = new GridBuilder()
+ const rows = queries.tiles.each()
+ type Id = (typeof rows)[number]["entity"]["id"]
+ const entities = new Map<number, Id>()
+ for (const { entity, data } of rows) {
+ grid.claim(data.tile.get(), entity.id, useOf(data))
+ entities.set(entity.id, entity.id)
+ }
+ const halls = new Set<number>(queries.halls.each().map((row) => row.entity.id))
+ let coins = resources.treasury.get().coins
+ // What is left to spend this step: placing several things at once draws on the same stock.
+ const left: Record<string, number> = { ...resources.stock.get() }
+
+ const afford = (cost: Kind["cost"]): string | null => {
+ if (coins < cost.coins) return "Not enough coins"
+ for (const [g, n] of Object.entries(cost.materials)) if ((left[g] ?? 0) < (n ?? 0)) return `Not enough ${g}`
+ return null
+ }
+ const pay = (cost: Kind["cost"]) => {
+ coins -= cost.coins
+ for (const [g, n] of Object.entries(cost.materials)) left[g] = (left[g] ?? 0) - (n ?? 0)
+ }
+ /** Fells the trees under a tile about to be built on. */
+ const fell = (tile: { x: number; y: number; size: number }) => {
+ for (const c of cellsOf(tile)) {
+ if (useAt(grid.value(), c.x, c.y) !== "tree") continue
+ const tree = entities.get(ownerAt(grid.value(), c.x, c.y))
+ if (tree !== undefined) commands.despawn(tree)
+ }
+ }
+ const spawn = (draft: Parameters<typeof commands.spawn>[0], tile: { x: number; y: number; size: number }, use: "building" | "house" | "road") => {
+ fell(tile)
+ const id = commands.spawn(draft)
+ grid.claim(tile, id, use)
+ entities.set(id, id)
+ return id
+ }
+
+ edits: for (const edit of ui.edits.splice(0)) {
+ switch (edit.type) {
+ case "building": {
+ const kind = kinds[edit.kind]
+ const tile = { ...edit.cell, size: kind.size }
+ if (!kind.buildable) break
+ if (!unlocked(kind, resources.census.get())) {
+ ui.toast(`${kind.title} needs a bigger town`)
+ break
+ }
+ if (!canPlace(grid.value(), tile)) {
+ ui.toast("No room there")
+ break
+ }
+ const short = afford(kind.cost)
+ if (short) {
+ ui.toast(short)
+ break
+ }
+ pay(kind.cost)
+ const id = spawn(buildingDraft(kind, edit.cell), tile, "building")
+ commands.insert(id, startOf(kind), ...rolesOf(kind))
+ if (edit.open) ui.selected = id
+ break
+ }
+ case "homes": {
+ let short: string | null = null
+ for (const cell of edit.cells) {
+ const tile = { ...cell, size: 1 }
+ if (!canPlace(grid.value(), tile)) continue
+ short = afford(home.cost)
+ if (short) break
+ pay(home.cost)
+ const id = spawn(houseDraft(cell), tile, "house")
+ commands.insert(id, houseStart())
+ }
+ if (short) ui.toast(short)
+ break
+ }
+ case "roads": {
+ let short = false
+ for (const cell of edit.cells) {
+ const tile = { ...cell, size: 1 }
+ if (!canPlace(grid.value(), tile)) continue
+ if (coins < ROAD_COST) {
+ short = true
+ break
+ }
+ coins -= ROAD_COST
+ spawn(roadDraft(cell), tile, "road")
+ }
+ if (short) ui.toast("Not enough coins")
+ break
+ }
+ case "remove": {
+ if (!inside(edit.cell.x, edit.cell.y)) break
+ const use = useAt(grid.value(), edit.cell.x, edit.cell.y)
+ const owner = entities.get(ownerAt(grid.value(), edit.cell.x, edit.cell.y))
+ if (owner === undefined || use === "rock" || use === "water") break
+ if (halls.has(owner)) {
+ ui.toast("The town hall stays")
+ break
+ }
+ // A building's walkers and a farm's fields are its children, and go with it.
+ commands.despawn(owner)
+ entities.delete(owner)
+ for (let k = 0; k < grid.owner.length; k++) {
+ if (grid.owner[k] === owner) {
+ grid.owner[k] = 0
+ grid.use[k] = "empty"
+ }
+ }
+ if (ui.selected === owner) ui.selected = null
+ break
+ }
+ case "tax":
+ resources.policy.update((p) => ({ ...p, [edit.tier]: edit.rate }))
+ break
+ case "sell":
+ resources.policy.update((p) => ({ ...p, sells: edit.on ? [...p.sells.filter((g) => g !== edit.good), edit.good] : p.sells.filter((g) => g !== edit.good) }))
+ break
+ case "reserve":
+ resources.policy.update((p) => ({ ...p, reserve: edit.amount }))
+ break
+ case "newTown": {
+ for (const id of entities.values()) commands.despawn(id)
+ entities.clear()
+ const land = generate(edit.seed)
+ for (const c of land.water) commands.spawn(waterDraft(c))
+ for (const t of land.trees) commands.spawn(treeDraft(t.cell, t.growth))
+ for (const r of land.rocks) commands.spawn(rockDraft(r.cell, r.ore, ROCK_AMOUNT))
+ for (const c of land.roads) commands.spawn(roadDraft(c))
+ const hall = kinds.townhall
+ const id = commands.spawn(buildingDraft(hall, land.hall))
+ commands.insert(id, ...rolesOf(hall))
+ const stock: Amounts = amounts(start.stock)
+ commands.insert(id, Game.Command.entry(TownHall, {}), Game.Command.entry(Status, "idle"), Game.Command.entry(Inventory, { stock, accepts: goodIds, cap: hall.holds?.cap ?? 60 }))
+ coins = start.coins
+ resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0 })
+ resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, reserve: trade.reserve })
+ resources.rng.set(edit.seed)
+ ui.selected = null
+ // Nothing else this step: the new land is not on the grid yet.
+ break edits
+ }
+ }
+ }
+ resources.treasury.set({ coins })
+ }
+)
diff --git a/src/sim/index.ts b/src/sim/index.ts
new file mode 100644
index 0000000..b32eb14
--- /dev/null
+++ b/src/sim/index.ts
@@ -0,0 +1,48 @@
+/**
+ * The simulation, one fixed step at a time. Nothing here touches the
+ * renderer, so it runs headless too.
+ */
+import { Game, Time } from "../schema.ts"
+import { ApplyEdits } from "./edits.ts"
+import { Deliver, Dispatch } from "./logistics.ts"
+import { Collect, Households, TakeCensus } from "./town.ts"
+import { SendWalkers, Walk, Wander } from "./walkers.ts"
+import { AssignStaff, CountStock, Grow, IndexGrid, Plant, Raise, Spread, Work } from "./work.ts"
+
+export const AdvanceTime = Game.System(
+ "Town/AdvanceTime",
+ { resources: { time: Game.System.writeResource(Time) } },
+ ({ resources }) => {
+ resources.time.update((t) => ({ tick: t.tick + 1 }))
+ }
+)
+
+export const simulate = Game.Schedule(
+ AdvanceTime,
+ // Edits see the stock as the last step left it, and index the grid themselves.
+ ApplyEdits,
+ Game.Schedule.applyDeferred(),
+ IndexGrid,
+ Raise,
+ AssignStaff,
+ Grow,
+ Work,
+ Plant,
+ Spread,
+ Dispatch,
+ SendWalkers,
+ Game.Schedule.applyDeferred(),
+ Walk,
+ Deliver,
+ Wander,
+ Game.Schedule.applyDeferred(),
+ Households,
+ Collect,
+ CountStock,
+ TakeCensus
+)
+
+export { CELL_STEPS } from "./shared.ts"
+export { SITE_SHARE } from "./work.ts"
+export { unlocked } from "./edits.ts"
+export { capacity, met, satisfaction, taxOf } from "./town.ts"
diff --git a/src/sim/logistics.ts b/src/sim/logistics.ts
new file mode 100644
index 0000000..916e7b6
--- /dev/null
+++ b/src/sim/logistics.ts
@@ -0,0 +1,216 @@
+/**
+ * Carriers: every good that moves walks along the roads in a carrier's
+ * crate. What a building wants — a site's materials, a workshop's input, a
+ * market's provisions — is a demand; a producer sends what it makes to the
+ * nearest demand for it, or else to the nearest storage with room, and a
+ * storage sends what it holds to the nearest demands it can meet. Crates
+ * already on their way count against a demand, so no one is sent twice.
+ */
+import { goods, goodIds, provisions, type GoodId } from "../content.ts"
+import { doors, nearest, pathTo, reach, type Reach } from "../grid.ts"
+import type { Point } from "../iso.ts"
+import {
+ Carriers, Errand, Figure, Game, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, WalkerOf, maybe
+} from "../schema.ts"
+import { CELL_STEPS } from "./shared.ts"
+
+/** The most a carrier takes at once. */
+const LOAD = 4
+
+export const Dispatch = Game.System(
+ "Town/Dispatch",
+ {
+ queries: {
+ senders: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ inventory: Game.Query.write(Inventory),
+ carriers: Game.Query.read(Carriers),
+ storage: Game.Query.optional(Storage),
+ recipe: Game.Query.optional(Recipe)
+ },
+ without: [Site, Rising]
+ }),
+ wanting: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ inventory: Game.Query.optional(Inventory),
+ recipe: Game.Query.optional(Recipe),
+ service: Game.Query.optional(Service),
+ storage: Game.Query.optional(Storage)
+ },
+ without: [Site, Rising]
+ }),
+ sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),
+ errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })
+ },
+ resources: { grid: Game.System.readResource(Grid) }
+ },
+ ({ queries, resources, commands }) => {
+ const grid = resources.grid.get()
+ const out = new Map<number, number>()
+ const incoming = new Map<string, number>()
+ const inbound = (target: number, good: GoodId) => incoming.get(`${target}:${good}`) ?? 0
+ const expect = (target: number, good: GoodId, count: number) => incoming.set(`${target}:${good}`, inbound(target, good) + count)
+ for (const { data } of queries.errands.each()) {
+ const errand = data.errand.get()
+ out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
+ if (!errand.back) expect(errand.target, errand.good, errand.count)
+ }
+
+ type Id = ReturnType<typeof queries.sites.each>[number]["entity"]["id"]
+ // What every building wants, nearest first once a sender is known.
+ interface Want {
+ readonly id: Id
+ readonly doors: ReadonlyArray<Point>
+ readonly good: GoodId
+ readonly want: () => number
+ readonly site: boolean
+ }
+ const wants: Array<Want> = []
+ for (const { entity, data } of queries.sites.each()) {
+ const site = data.site.get()
+ const ds = doors(grid, data.tile.get())
+ for (const g of goodIds) if (site.owed[g] > 0) wants.push({ id: entity.id, doors: ds, good: g, site: true, want: () => site.owed[g] - inbound(entity.id, g) })
+ }
+ const rooms: Array<{ readonly id: Id; readonly doors: ReadonlyArray<Point>; readonly room: (g: GoodId) => number }> = []
+ for (const { entity, data } of queries.wanting.each()) {
+ const inventory = maybe(data.inventory)
+ if (!inventory) continue
+ const ds = doors(grid, data.tile.get())
+ if (ds.length === 0) continue
+ const recipe = maybe(data.recipe)
+ const space = (g: GoodId) => inventory.cap - inventory.stock[g] - inbound(entity.id, g)
+ if (data.storage.present) rooms.push({ id: entity.id, doors: ds, room: space })
+ else if (recipe && recipe.input !== null) {
+ const g = recipe.input
+ wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
+ } else if (maybe(data.service)?.service === "goods") {
+ for (const g of provisions) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
+ }
+ }
+
+ const send = (from: { readonly id: Id; readonly roads: Reach }, to: { readonly id: Id; readonly cell: Point }, good: GoodId, count: number) => {
+ const draft = Game.Command.spawn(
+ [Figure, { role: "carrier", color: goods[good].color }],
+ [Route, { cells: pathTo(from.roads, to.cell), index: 0, step: 0 }],
+ [Errand, { target: Game.Entity.handle(to.id, Tile), good, count, back: false }]
+ )
+ commands.spawn(Game.Command.relate(draft, WalkerOf, from.id))
+ out.set(from.id, (out.get(from.id) ?? 0) + 1)
+ expect(to.id, good, count)
+ }
+
+ for (const { entity, data } of queries.senders.each()) {
+ const carriers = data.carriers.get().count
+ if ((out.get(entity.id) ?? 0) >= carriers) continue
+ const starts = doors(grid, data.tile.get())
+ if (starts.length === 0) continue
+ const roads = reach(grid, starts)
+ const inventory = data.inventory.get()
+ let stock = inventory.stock
+ const recipe = maybe(data.recipe)
+
+ // A storage meets demands with what it holds; anyone else sends on what it made.
+ // A producer waits for a full load (or a full shelf) so its carriers do not walk with one crate.
+ const ready = recipe ? stock[recipe.output] >= Math.min(LOAD, inventory.cap - recipe.batch) : false
+ const offers: ReadonlyArray<GoodId> = data.storage.present ? goodIds.filter((g) => stock[g] > 0) : recipe && ready ? [recipe.output] : []
+ for (const good of offers) {
+ if ((out.get(entity.id) ?? 0) >= carriers) break
+ let best: { readonly id: Id; readonly cell: Point; readonly distance: number; readonly count: number; readonly site: boolean } | null = null
+ for (const w of wants) {
+ if (w.good !== good || w.id === entity.id) continue
+ const count = Math.min(LOAD, stock[good], w.want())
+ if (count <= 0) continue
+ const found = nearest(roads, w.doors)
+ // Sites come first, then whoever is nearest.
+ if (found && (best === null || (w.site && !best.site) || (w.site === best.site && found.distance < best.distance))) best = { id: w.id, ...found, count, site: w.site }
+ }
+ if (best === null && !data.storage.present) {
+ for (const r of rooms) {
+ if (r.id === entity.id) continue
+ const count = Math.min(LOAD, stock[good], r.room(good))
+ if (count <= 0) continue
+ const found = nearest(roads, r.doors)
+ if (found && (best === null || found.distance < best.distance)) best = { id: r.id, ...found, count, site: false }
+ }
+ }
+ if (best === null) continue
+ send({ id: entity.id, roads }, best, good, best.count)
+ stock = { ...stock, [good]: stock[good] - best.count }
+ }
+ if (stock !== inventory.stock) data.inventory.set({ ...inventory, stock })
+ }
+ }
+)
+
+const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number }) => route.index >= route.cells.length - 1
+
+/** The way back from where a walker is now, mid-step or not. */
+export const turnAround = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number; readonly step: number }) => {
+ const behind = route.cells.slice(0, route.index + 1).reverse()
+ const ahead = route.cells[route.index + 1]
+ return route.step > 0 && ahead
+ ? { cells: [ahead, ...behind], index: 0, step: CELL_STEPS - route.step }
+ : { cells: behind, index: 0, step: 0 }
+}
+
+const TargetRead = Game.Query({ selection: { tile: Game.Query.read(Tile) } })
+
+/**
+ * A carrier hands its crate over: to a site, towards what it is owed; to
+ * anyone else, as much as they have room for. Then it walks back, and puts
+ * whatever it still carries back where it came from.
+ */
+export const Deliver = Game.System(
+ "Town/Deliver",
+ {
+ queries: {
+ carriers: Game.Query({ selection: { route: Game.Query.write(Route), errand: Game.Query.write(Errand), home: Game.Query.readRelation(WalkerOf) } }),
+ inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, without: [Site] }),
+ sites: Game.Query({ selection: { site: Game.Query.write(Site) } })
+ }
+ },
+ ({ queries, commands, lookup }) => {
+ for (const { entity, data } of queries.carriers.each()) {
+ const route = data.route.get()
+ const errand = data.errand.get()
+ if (errand.back) {
+ if (!arrived(route)) continue
+ const home = queries.inventories.get(data.home.get())
+ if (home.ok && errand.count > 0) {
+ const inv = home.value.data.inventory.get()
+ const room = inv.cap - inv.stock[errand.good]
+ home.value.data.inventory.set({ ...inv, stock: { ...inv.stock, [errand.good]: inv.stock[errand.good] + Math.min(room, errand.count) } })
+ }
+ commands.despawn(entity.id)
+ continue
+ }
+ const target = lookup.getHandle(errand.target, TargetRead)
+ if (!target.ok) {
+ // Nowhere to take it: carry it home.
+ data.route.set(turnAround(route))
+ data.errand.set({ ...errand, back: true })
+ continue
+ }
+ if (!arrived(route)) continue
+ let handed = 0
+ const site = queries.sites.get(target.value.entity.id)
+ const inventory = queries.inventories.get(target.value.entity.id)
+ if (site.ok) {
+ const s = site.value.data.site.get()
+ handed = Math.min(errand.count, s.owed[errand.good])
+ site.value.data.site.set({ ...s, owed: { ...s.owed, [errand.good]: s.owed[errand.good] - handed } })
+ } else if (inventory.ok) {
+ const inv = inventory.value.data.inventory.get()
+ if (inv.accepts.includes(errand.good)) {
+ handed = Math.min(errand.count, inv.cap - inv.stock[errand.good])
+ inventory.value.data.inventory.set({ ...inv, stock: { ...inv.stock, [errand.good]: inv.stock[errand.good] + handed } })
+ }
+ }
+ data.route.set({ cells: [...route.cells].reverse(), index: 0, step: 0 })
+ data.errand.set({ ...errand, count: errand.count - handed, back: true })
+ }
+ }
+)
+
diff --git a/src/sim/shared.ts b/src/sim/shared.ts
new file mode 100644
index 0000000..7f8a0a0
--- /dev/null
+++ b/src/sim/shared.ts
@@ -0,0 +1,37 @@
+/** Queries and small helpers the simulation's systems share. */
+import { doors, type TileLike, type Use } from "../grid.ts"
+import { Field, Game, House, Road, Rock, Tile, Tree, Water, type GridValue } from "../schema.ts"
+
+/** Every tile, with enough to tell what it is. */
+export const TileRead = Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ road: Game.Query.optional(Road),
+ house: Game.Query.optional(House),
+ tree: Game.Query.optional(Tree),
+ rock: Game.Query.optional(Rock),
+ water: Game.Query.optional(Water),
+ field: Game.Query.optional(Field)
+ }
+})
+
+export const useOf = (data: {
+ readonly road: { readonly present: boolean }
+ readonly house: { readonly present: boolean }
+ readonly tree: { readonly present: boolean }
+ readonly rock: { readonly present: boolean }
+ readonly water: { readonly present: boolean }
+ readonly field: { readonly present: boolean }
+}): Use =>
+ data.road.present ? "road"
+ : data.house.present ? "house"
+ : data.tree.present ? "tree"
+ : data.rock.present ? "rock"
+ : data.water.present ? "water"
+ : data.field.present ? "field"
+ : "building"
+
+export const connected = (grid: GridValue, tile: TileLike): boolean => doors(grid, tile).length > 0
+
+/** A walker's steps from one cell's centre to the next: three to a unit, so it moves on the lattice. */
+export const CELL_STEPS = 48
diff --git a/src/sim/town.ts b/src/sim/town.ts
new file mode 100644
index 0000000..e8a16a9
--- /dev/null
+++ b/src/sim/town.ts
@@ -0,0 +1,170 @@
+/**
+ * The town: homes grow, level up, or empty depending on what reaches them;
+ * taxes are collected from homes connected to the town hall and upkeep paid
+ * for every standing building; and the census counts it all.
+ */
+import { appealOf, goods, home, kinds, LEDGER_TICKS, TRADE_LOAD, type Need, type Tier } from "../content.ts"
+import { doors, key, reach } from "../grid.ts"
+import { Building, Census, Game, Grid, House, Inventory, Ledger, Policy, Rising, Site, Staff, Storage, Tile, Time, TownHall, Treasury } from "../schema.ts"
+import { connected } from "./shared.ts"
+
+interface Needs {
+ readonly tier: Tier
+ readonly food: number
+ readonly bread: number
+ readonly cloth: number
+ readonly faith: number
+}
+
+export const met = (h: Needs, need: Need): boolean => h[need] > 0
+
+/** The share of its tier's needs a home has met, 0 → 1. */
+export const satisfaction = (h: Needs, tier: Tier = h.tier): number => {
+ const needs = home.tiers[tier].needs
+ return needs.filter((n) => met(h, n)).length / needs.length
+}
+
+export interface Rates {
+ readonly settlers: number
+ readonly citizens: number
+}
+const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rates.citizens)
+
+/**
+ * Residents a home holds at its tier and satisfaction: half when nothing is
+ * met, all when everything is; fewer under high taxes, and up to all of
+ * them under low ones.
+ */
+export const capacity = (h: Needs, rates: Rates): number => {
+ const max = home.tiers[h.tier].residents
+ return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h)) * appealOf(rateOf(rates, h.tier)))))
+}
+
+/** Coins a home pays a minute. */
+export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates): number =>
+ h.residents * home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * (0.25 + 0.75 * satisfaction(h))
+
+/**
+ * Needs wear off. Every so often a home settles: settlers whose every
+ * citizens' need is met become citizens; citizens missing more than one need
+ * go back to being settlers. One resident moves in or out towards what the
+ * home holds; everyone leaves a home with no road.
+ */
+export const Households = Game.System(
+ "Town/Households",
+ {
+ queries: { homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.write(House) }, without: [Site, Rising] }) },
+ resources: { grid: Game.System.readResource(Grid), policy: Game.System.readResource(Policy) }
+ },
+ ({ queries, resources }) => {
+ const grid = resources.grid.get()
+ const rates = resources.policy.get()
+ for (const { data } of queries.homes.each()) {
+ const h = data.house.get()
+ const next = {
+ ...h,
+ clock: h.clock + 1,
+ food: Math.max(0, h.food - 1),
+ bread: Math.max(0, h.bread - 1),
+ cloth: Math.max(0, h.cloth - 1),
+ faith: Math.max(0, h.faith - 1)
+ }
+ if (next.clock % home.settle === 0) {
+ if (next.tier === 1 && satisfaction(next, 2) === 1) next.tier = 2
+ else if (next.tier === 2 && satisfaction(next) < 2 / 3) next.tier = 1
+ const cap = connected(grid, data.tile.get()) ? capacity(next, rates) : 0
+ next.residents += Math.sign(cap - next.residents)
+ }
+ data.house.set(next)
+ }
+ }
+)
+
+/**
+ * Every `LEDGER_TICKS`: taxes in from homes the town hall can reach by road,
+ * coins from traders for what the town sells beyond its reserve (taken from
+ * its storage, fullest first), and upkeep out for every standing building.
+ */
+export const Collect = Game.System(
+ "Town/Collect",
+ {
+ queries: {
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising] }),
+ buildings: Game.Query({ selection: { building: Game.Query.read(Building) }, without: [Site] }),
+ halls: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [TownHall] }),
+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ grid: Game.System.readResource(Grid),
+ policy: Game.System.readResource(Policy),
+ treasury: Game.System.writeResource(Treasury),
+ ledger: Game.System.writeResource(Ledger)
+ }
+ },
+ ({ queries, resources }) => {
+ if (resources.time.get().tick % LEDGER_TICKS !== 0) return
+ const grid = resources.grid.get()
+ const hall = queries.halls.each()[0]
+ const roads = hall ? reach(grid, doors(grid, hall.data.tile.get())) : null
+ const share = LEDGER_TICKS / (60 * 60)
+ let taxes = 0
+ for (const { data } of queries.homes.each()) {
+ const reached = roads !== null && doors(grid, data.tile.get()).some((c) => roads.distance[key(c.x, c.y)]! >= 0)
+ if (reached) taxes += taxOf(data.house.get(), resources.policy.get())
+ }
+ let upkeep = 0
+ for (const { data } of queries.buildings.each()) upkeep += kinds[data.building.get().kind].upkeep
+ // Traders take the surplus.
+ const policy = resources.policy.get()
+ const stores = queries.stores.each()
+ let sold = 0
+ for (const good of policy.sells) {
+ const held = stores.reduce((sum, { data }) => sum + data.inventory.get().stock[good], 0)
+ let surplus = Math.min(TRADE_LOAD, held - policy.reserve)
+ if (surplus <= 0) continue
+ sold += surplus * goods[good].price
+ for (const { data } of [...stores].sort((a, b) => b.data.inventory.get().stock[good] - a.data.inventory.get().stock[good])) {
+ if (surplus <= 0) break
+ const inv = data.inventory.get()
+ const take = Math.min(surplus, inv.stock[good])
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - take } })
+ surplus -= take
+ }
+ }
+ resources.treasury.update((t) => ({ coins: t.coins + Math.round(taxes * share) + sold - Math.round(upkeep * share) }))
+ resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(sold / share), upkeep: Math.round(upkeep) })
+ }
+)
+
+export const TakeCensus = Game.System(
+ "Town/TakeCensus",
+ {
+ queries: {
+ homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising] }),
+ workplaces: Game.Query({ selection: { staff: Game.Query.read(Staff) }, without: [Site, Rising] })
+ },
+ resources: { census: Game.System.writeResource(Census) }
+ },
+ ({ queries, resources }) => {
+ let homes = 0
+ let settlers = 0
+ let citizens = 0
+ const needs = { food: 0, bread: 0, cloth: 0, faith: 0 }
+ for (const { data } of queries.homes.each()) {
+ const h = data.house.get()
+ homes += 1
+ if (h.tier === 1) settlers += h.residents
+ else citizens += h.residents
+ for (const n of ["food", "bread", "cloth", "faith"] as const) if (met(h, n)) needs[n] += 1
+ }
+ let jobs = 0
+ let employed = 0
+ for (const { data } of queries.workplaces.each()) {
+ const s = data.staff.get()
+ jobs += s.needed
+ employed += s.assigned
+ }
+ resources.census.set({ homes, settlers, citizens, jobs, employed, ...needs })
+ }
+)
diff --git a/src/sim/walkers.ts b/src/sim/walkers.ts
new file mode 100644
index 0000000..385db82
--- /dev/null
+++ b/src/sim/walkers.ts
@@ -0,0 +1,226 @@
+/**
+ * Walking: every walker steps along its route; service buildings send a
+ * walker out now and then, who wanders the roads serving the homes beside
+ * it — a market's (or the town hall's) with a basket of provisions, a
+ * chapel's with faith — and walks home when its range is walked.
+ */
+import * as Random from "@typeonce/bevy-ts-math/Random"
+
+import { amounts, categoryColor, each, home, kinds, provisions, total, type Amounts, type Need } from "../content.ts"
+import { DIRS, doors, isRoad, key, nearest, pathTo, reach } from "../grid.ts"
+import { inside, type Point } from "../iso.ts"
+import {
+ Building, Figure, Game, Grid, House, Inventory, Recipe, Rising, Rng, Roam, Route, Service, Site, Staff, Status, Tile, WalkerOf,
+ maybe, type Status as StatusValue
+} from "../schema.ts"
+import { CELL_STEPS } from "./shared.ts"
+
+/** Steps a walker takes each tick: 1.25 cells a second. */
+const WALK = 1
+/** Of each provision, the most a walker's basket holds. */
+const BASKET = 6
+
+/** Every walker steps along its route; one whose next cell is no longer road is lost. */
+export const Walk = Game.System(
+ "Town/Walk",
+ {
+ queries: { walkers: Game.Query({ selection: { route: Game.Query.write(Route) } }) },
+ resources: { grid: Game.System.readResource(Grid) }
+ },
+ ({ queries, resources, commands }) => {
+ const grid = resources.grid.get()
+ for (const { entity, data } of queries.walkers.each()) {
+ const route = data.route.get()
+ const last = route.cells.length - 1
+ if (route.index >= last) continue
+ const next = route.cells[route.index + 1]!
+ if (!isRoad(grid, next.x, next.y)) {
+ commands.despawn(entity.id)
+ continue
+ }
+ const step = route.step + WALK
+ if (step < CELL_STEPS) data.route.set({ ...route, step })
+ else {
+ const index = route.index + 1
+ data.route.set({ ...route, index, step: index >= last ? 0 : step - CELL_STEPS })
+ }
+ }
+ }
+)
+
+/**
+ * A staffed service building sends one walker at a time, every `interval`
+ * steps. A provisions walker fills its basket from the building's stock, and
+ * only goes when there is something to hand out.
+ */
+export const SendWalkers = Game.System(
+ "Town/SendWalkers",
+ {
+ queries: {
+ services: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ building: Game.Query.read(Building),
+ staff: Game.Query.read(Staff),
+ service: Game.Query.write(Service),
+ status: Game.Query.write(Status),
+ inventory: Game.Query.optional(Inventory),
+ recipe: Game.Query.optional(Recipe)
+ },
+ without: [Site, Rising]
+ }),
+ inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] }),
+ walkers: Game.Query({ selection: { roam: Game.Query.read(Roam), home: Game.Query.readRelation(WalkerOf) } })
+ },
+ resources: { grid: Game.System.readResource(Grid) }
+ },
+ ({ queries, resources, commands }) => {
+ const grid = resources.grid.get()
+ const out = new Set<number>()
+ for (const { data } of queries.walkers.each()) out.add(data.home.get())
+
+ for (const { entity, data } of queries.services.each()) {
+ const service = data.service.get()
+ const staff = data.staff.get()
+ const starts = doors(grid, data.tile.get())
+ const stock = maybe(data.inventory)?.stock
+ const staffed = staff.needed === 0 || staff.assigned > 0
+ const basket: Amounts = each((g) => (service.service === "goods" && stock && provisions.includes(g) ? Math.min(BASKET, stock[g]) : 0))
+ const goes = service.service === "faith" || total(basket) > 0
+ if (!maybe(data.recipe)) {
+ const status: StatusValue = starts.length === 0
+ ? "unconnected"
+ : !staffed
+ ? "unstaffed"
+ : out.has(entity.id)
+ ? "working"
+ : goes
+ ? "idle"
+ : "starved"
+ if (data.status.get() !== status) data.status.set(status)
+ }
+
+ const cooldown = Math.max(0, service.cooldown - 1)
+ if (cooldown === 0 && !out.has(entity.id) && starts.length > 0 && staffed && goes) {
+ const color = categoryColor[kinds[data.building.get().kind].category]
+ const draft = Game.Command.spawn(
+ [Figure, { role: "walker", color }],
+ [Route, { cells: [starts[0]!], index: 0, step: 0 }],
+ [Roam, { service: service.service, left: service.range, basket, back: false }]
+ )
+ commands.spawn(Game.Command.relate(draft, WalkerOf, entity.id))
+ const inv = queries.inventories.get(entity.id)
+ if (inv.ok && total(basket) > 0) {
+ const i = inv.value.data.inventory.get()
+ inv.value.data.inventory.set({ ...i, stock: each((g) => i.stock[g] - basket[g]) })
+ }
+ data.service.set({ ...service, cooldown: service.interval })
+ } else if (cooldown !== service.cooldown) data.service.set({ ...service, cooldown })
+ }
+ }
+)
+
+const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number }) => route.index >= route.cells.length - 1
+
+/**
+ * A service walker wanders: at each cell it serves the homes beside it, then
+ * picks a road onward at random (never straight back, unless it must). Once
+ * its range is walked, or its basket is empty, it heads home by the shortest
+ * road, and puts back what it still carries.
+ *
+ * A home low on a need takes what meets it: bread or else fish for food
+ * (bread meets the citizens' bread need too), cloth for cloth; a chapel's
+ * walker brings faith.
+ */
+export const Wander = Game.System(
+ "Town/Wander",
+ {
+ queries: {
+ walkers: Game.Query({ selection: { route: Game.Query.write(Route), roam: Game.Query.write(Roam), home: Game.Query.readRelation(WalkerOf) } }),
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.write(House) }, without: [Site, Rising] }),
+ buildings: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Service] }),
+ inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] })
+ },
+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng) }
+ },
+ ({ queries, resources, commands }) => {
+ const grid = resources.grid.get()
+ const random = Random.make(resources.rng.get())
+ const homes = new Map<number, ReturnType<typeof queries.homes.each>[number]>()
+ for (const row of queries.homes.each()) {
+ const t = row.data.tile.get()
+ homes.set(key(t.x, t.y), row)
+ }
+ const low = (left: number, need: Need) => left < home.lasts[need] / 2
+
+ for (const { entity, data } of queries.walkers.each()) {
+ const route = data.route.get()
+ if (!arrived(route)) continue
+ const roam = data.roam.get()
+ const from = data.home.get()
+
+ if (roam.back) {
+ const inv = queries.inventories.get(from)
+ if (inv.ok && total(roam.basket) > 0) {
+ const i = inv.value.data.inventory.get()
+ inv.value.data.inventory.set({ ...i, stock: each((g) => Math.min(i.cap, i.stock[g] + roam.basket[g])) })
+ }
+ commands.despawn(entity.id)
+ continue
+ }
+
+ // Serve the homes beside this cell.
+ const cell = route.cells[route.cells.length - 1]!
+ const basket: Record<string, number> = { ...roam.basket }
+ for (const d of DIRS) {
+ const x = cell.x + d.x
+ const y = cell.y + d.y
+ const row = inside(x, y) ? homes.get(key(x, y)) : undefined
+ if (!row) continue
+ const h = { ...row.data.house.get() }
+ if (roam.service === "faith") h.faith = home.lasts.faith
+ else {
+ if ((low(h.food, "food") || (h.tier === 2 && low(h.bread, "bread"))) && (basket.bread ?? 0) > 0) {
+ basket.bread = (basket.bread ?? 0) - 1
+ h.food = home.lasts.food
+ h.bread = home.lasts.bread
+ } else if (low(h.food, "food") && (basket.fish ?? 0) > 0) {
+ basket.fish = (basket.fish ?? 0) - 1
+ h.food = home.lasts.food
+ }
+ if (low(h.cloth, "cloth") && (basket.cloth ?? 0) > 0) {
+ basket.cloth = (basket.cloth ?? 0) - 1
+ h.cloth = home.lasts.cloth
+ }
+ }
+ row.data.house.set(h)
+ }
+ const left = roam.left - 1
+ const carrying = amounts(basket)
+ if (left > 0 && (roam.service !== "goods" || total(carrying) > 0)) {
+ const previous = route.cells.length >= 2 ? route.cells[route.cells.length - 2]! : null
+ const onward = DIRS
+ .map((d) => ({ x: cell.x + d.x, y: cell.y + d.y }))
+ .filter((c) => isRoad(grid, c.x, c.y) && !(previous && c.x === previous.x && c.y === previous.y))
+ const next = random.pick(onward) ?? previous
+ if (next) {
+ data.route.set({ cells: [cell, next], index: 0, step: 0 })
+ data.roam.set({ ...roam, left, basket: carrying })
+ continue
+ }
+ }
+
+ // Head home.
+ const building = queries.buildings.get(from)
+ const way = reach(grid, [cell])
+ const door = building.ok ? nearest(way, doors(grid, building.value.data.tile.get())) : null
+ if (!door) {
+ commands.despawn(entity.id)
+ continue
+ }
+ data.route.set({ cells: pathTo(way, door.cell), index: 0, step: 0 })
+ data.roam.set({ ...roam, left: 0, basket: carrying, back: true })
+ }
+ resources.rng.set(random.state)
+ }
+)
diff --git a/src/sim/work.ts b/src/sim/work.ts
new file mode 100644
index 0000000..560f248
--- /dev/null
+++ b/src/sim/work.ts
@@ -0,0 +1,319 @@
+/**
+ * Building and working: the grid and the town's stock are indexed, sites
+ * whose materials are in start going up, workers are assigned, recipes
+ * turn inputs (or the land) into goods, planters sow trees and fields, and
+ * what is sown grows.
+ */
+import * as Random from "@typeonce/bevy-ts-math/Random"
+
+import { fieldDraft, treeDraft } from "../archetypes.ts"
+import { amounts, BUILD_TICKS, goodIds, GROWN, ticks, total, type Amounts } from "../content.ts"
+import { around, DIRS, GridBuilder, key, ownerAt, useAt } from "../grid.ts"
+import {
+ Field, FieldOf, Game, Gatherer, Grid, House, Inventory, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock,
+ Storage, Tile, Time, Tree, maybe, type Status as StatusValue
+} from "../schema.ts"
+import { connected, TileRead, useOf } from "./shared.ts"
+
+/** What stands where, for every system after it this step. */
+export const IndexGrid = Game.System(
+ "Town/IndexGrid",
+ { queries: { tiles: TileRead }, resources: { grid: Game.System.writeResource(Grid) } },
+ ({ queries, resources }) => {
+ const grid = new GridBuilder()
+ for (const { entity, data } of queries.tiles.each()) grid.claim(data.tile.get(), entity.id, useOf(data))
+ resources.grid.set(grid.value())
+ }
+)
+
+/** The goods in every storage, summed. */
+export const CountStock = Game.System(
+ "Town/CountStock",
+ {
+ queries: { stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] }) },
+ resources: { stock: Game.System.writeResource(Stock) }
+ },
+ ({ queries, resources }) => {
+ const sum: Record<string, number> = { ...amounts({}) }
+ for (const { data } of queries.stores.each()) {
+ const s = data.inventory.get().stock
+ for (const g of goodIds) sum[g] = (sum[g] ?? 0) + s[g]
+ }
+ resources.stock.set(sum as Amounts)
+ }
+)
+
+// ── Going up ──────────────────────────────────────────────────────────────
+
+/** Where a site's walls are once its materials are in: it goes on rising from here. */
+export const SITE_SHARE = 0.35
+
+export const Raise = Game.System(
+ "Town/Raise",
+ {
+ queries: {
+ sites: Game.Query({ selection: { site: Game.Query.read(Site) } }),
+ rising: Game.Query({ selection: { rising: Game.Query.write(Rising), status: Game.Query.optional(Status) } })
+ }
+ },
+ ({ queries, commands }) => {
+ for (const { entity, data } of queries.sites.each()) {
+ if (total(data.site.get().owed) > 0) continue
+ commands.remove(entity.id, Site)
+ commands.insert(entity.id, Game.Command.entry(Rising, { ticks: Math.round(BUILD_TICKS * SITE_SHARE) }))
+ }
+ for (const { entity, data } of queries.rising.each()) {
+ const ticks = data.rising.get().ticks + 1
+ if (ticks >= BUILD_TICKS) {
+ commands.remove(entity.id, Rising)
+ // Up and standing; its work (if it has any) says otherwise from here on.
+ if (data.status.present) commands.insert(entity.id, Game.Command.entry(Status, "idle"))
+ } else data.rising.set({ ticks })
+ }
+ }
+)
+
+// ── Workers ───────────────────────────────────────────────────────────────
+
+/** Residents go to work in the order buildings were placed, as many as each needs while any are left. */
+export const AssignStaff = Game.System(
+ "Town/AssignStaff",
+ {
+ queries: {
+ homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising] }),
+ workplaces: Game.Query({ selection: { tile: Game.Query.read(Tile), staff: Game.Query.write(Staff) }, without: [Site, Rising] })
+ },
+ resources: { grid: Game.System.readResource(Grid) }
+ },
+ ({ queries, resources }) => {
+ const grid = resources.grid.get()
+ let pool = 0
+ for (const { data } of queries.homes.each()) pool += data.house.get().residents
+ for (const { data } of queries.workplaces.each()) {
+ const staff = data.staff.get()
+ const assigned = connected(grid, data.tile.get()) ? Math.min(staff.needed, pool) : 0
+ pool -= assigned
+ if (assigned !== staff.assigned) data.staff.set({ ...staff, assigned })
+ }
+ }
+)
+
+// ── Recipes ───────────────────────────────────────────────────────────────
+
+/**
+ * One step of every recipe. A job starts when there is room for what it
+ * makes, its input is in, and (for a gatherer) the land has what it needs
+ * within reach: a grown tree is felled, a rock chipped, a ripe field
+ * reaped. Then the crew puts its worker-steps in; a full crew finishes in
+ * `period` steps.
+ */
+export const Work = Game.System(
+ "Town/Work",
+ {
+ queries: {
+ workshops: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ staff: Game.Query.read(Staff),
+ recipe: Game.Query.write(Recipe),
+ inventory: Game.Query.write(Inventory),
+ status: Game.Query.write(Status),
+ gatherer: Game.Query.optional(Gatherer)
+ },
+ without: [Site, Rising]
+ }),
+ trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),
+ rocks: Game.Query({ selection: { rock: Game.Query.write(Rock) } }),
+ fields: Game.Query({ selection: { field: Game.Query.write(Field) } })
+ },
+ resources: { grid: Game.System.readResource(Grid) }
+ },
+ ({ queries, resources, commands }) => {
+ const grid = resources.grid.get()
+ const trees = new Map(queries.trees.each().map((row) => [row.entity.id as number, row]))
+ const rocks = new Map(queries.rocks.each().map((row) => [row.entity.id as number, row]))
+ const fields = new Map(queries.fields.each().map((row) => [row.entity.id as number, row]))
+ const used = new Set<number>()
+
+ /** Takes what a gatherer needs from the land within reach, or says there is none. */
+ const gather = (source: "tree" | "stone" | "ore" | "field" | "water", tile: { x: number; y: number; size: number }, radius: number): boolean => {
+ for (const c of around(tile, radius)) {
+ const use = useAt(grid, c.x, c.y)
+ const id = ownerAt(grid, c.x, c.y)
+ if (used.has(id)) continue
+ if (source === "water" && use === "water") return true
+ if (source === "tree" && use === "tree") {
+ const tree = trees.get(id)
+ if (!tree || tree.data.tree.get().growth < GROWN.tree) continue
+ commands.despawn(tree.entity.id)
+ used.add(id)
+ return true
+ }
+ if ((source === "stone" || source === "ore") && use === "rock") {
+ const rock = rocks.get(id)
+ if (!rock) continue
+ const r = rock.data.rock.get()
+ if (r.ore !== (source === "ore") || r.amount <= 0) continue
+ if (r.amount <= 1) {
+ commands.despawn(rock.entity.id)
+ used.add(id)
+ } else rock.data.rock.set({ ...r, amount: r.amount - 1 })
+ return true
+ }
+ if (source === "field" && use === "field") {
+ const field = fields.get(id)
+ if (!field || field.data.field.get().growth < GROWN.field) continue
+ field.data.field.set({ growth: 0 })
+ used.add(id)
+ return true
+ }
+ }
+ return false
+ }
+
+ for (const { data } of queries.workshops.each()) {
+ const tile = data.tile.get()
+ const staff = data.staff.get()
+ const gatherer = maybe(data.gatherer)
+ let recipe = data.recipe.get()
+ const inventory = data.inventory.get()
+ let stock = inventory.stock
+ const open = connected(grid, tile)
+ const room = stock[recipe.output] + recipe.batch <= inventory.cap
+ const fed = recipe.input === null || stock[recipe.input] >= recipe.inputs
+ let short = !fed
+
+ if (open && staff.assigned > 0 && recipe.progress === 0 && room && fed) {
+ if (gatherer && !gather(gatherer.source, tile, gatherer.radius)) short = true
+ else {
+ if (recipe.input !== null) stock = { ...stock, [recipe.input]: stock[recipe.input] - recipe.inputs }
+ recipe = { ...recipe, progress: 1 }
+ }
+ }
+ if (open && recipe.progress > 0 && staff.assigned > 0) {
+ const progress = recipe.progress + staff.assigned
+ if (progress > recipe.period * staff.needed) {
+ recipe = { ...recipe, progress: 0, made: recipe.made + 1 }
+ stock = { ...stock, [recipe.output]: stock[recipe.output] + recipe.batch }
+ } else recipe = { ...recipe, progress }
+ }
+ const status: StatusValue = !open
+ ? "unconnected"
+ : staff.assigned === 0
+ ? "unstaffed"
+ : recipe.progress > 0
+ ? "working"
+ : !room
+ ? "blocked"
+ : short
+ ? "starved"
+ : "idle"
+ data.recipe.set(recipe)
+ if (stock !== inventory.stock) data.inventory.set({ ...inventory, stock })
+ if (data.status.get() !== status) data.status.set(status)
+ }
+ }
+)
+
+// ── The land ──────────────────────────────────────────────────────────────
+
+/** A forester plants trees and a farm sows fields on free ground within reach, one at a time. */
+export const Plant = Game.System(
+ "Town/Plant",
+ {
+ queries: {
+ planters: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ staff: Game.Query.read(Staff),
+ planter: Game.Query.write(Planter),
+ status: Game.Query.write(Status),
+ recipe: Game.Query.optional(Recipe)
+ },
+ without: [Site, Rising]
+ })
+ },
+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng) }
+ },
+ ({ queries, resources, commands }) => {
+ const grid = resources.grid.get()
+ const random = Random.make(resources.rng.get())
+ const sown = new Set<number>()
+ for (const { entity, data } of queries.planters.each()) {
+ const tile = data.tile.get()
+ const staff = data.staff.get()
+ const planter = data.planter.get()
+ const open = connected(grid, tile)
+ const reach = around(tile, planter.radius)
+ const grown = reach.filter((c) => useAt(grid, c.x, c.y) === planter.what).length
+ const spots = reach.filter((c) => useAt(grid, c.x, c.y) === "empty" && !sown.has(key(c.x, c.y)))
+ // A forester has no recipe of its own: its status is its planting.
+ if (!maybe(data.recipe)) {
+ const status: StatusValue = !open ? "unconnected" : staff.assigned === 0 ? "unstaffed" : grown < planter.max && spots.length > 0 ? "working" : "idle"
+ if (data.status.get() !== status) data.status.set(status)
+ }
+ const cooldown = Math.max(0, planter.cooldown - 1)
+ if (cooldown > 0 || !open || staff.assigned === 0 || grown >= planter.max || spots.length === 0) {
+ if (cooldown !== planter.cooldown) data.planter.set({ ...planter, cooldown })
+ continue
+ }
+ const spot = random.pick(spots)!
+ sown.add(key(spot.x, spot.y))
+ if (planter.what === "tree") commands.spawn(treeDraft(spot, 0))
+ else commands.spawn(Game.Command.relate(fieldDraft(spot), FieldOf, entity.id))
+ data.planter.set({ ...planter, cooldown: planter.interval })
+ }
+ resources.rng.set(random.state)
+ }
+)
+
+/** How often a wild forest seeds a new tree. */
+const SPREAD_TICKS = ticks(1.5)
+
+/**
+ * Wild forests regrow: now and then a grown tree seeds an empty cell beside
+ * it, but only one that already has two trees around it, so forests fill
+ * back in and creep at their edges without seeding the open town. A cleared
+ * patch needs a forester.
+ */
+export const Spread = Game.System(
+ "Town/Spread",
+ {
+ queries: { trees: Game.Query({ selection: { tile: Game.Query.read(Tile), tree: Game.Query.read(Tree) } }) },
+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) }
+ },
+ ({ queries, resources, commands }) => {
+ if (resources.time.get().tick % SPREAD_TICKS !== 0) return
+ const grid = resources.grid.get()
+ const random = Random.make(resources.rng.get())
+ const grown = queries.trees.each().filter(({ data }) => data.tree.get().growth >= GROWN.tree)
+ const parent = random.pick(grown)
+ if (parent) {
+ const t = parent.data.tile.get()
+ const spot = random.pick(DIRS.map((d) => ({ x: t.x + d.x, y: t.y + d.y })).filter((c) => useAt(grid, c.x, c.y) === "empty"))
+ if (spot && DIRS.filter((d) => useAt(grid, spot.x + d.x, spot.y + d.y) === "tree").length >= 2) commands.spawn(treeDraft(spot, 0))
+ }
+ resources.rng.set(random.state)
+ }
+)
+
+/** Trees and fields grow until they are ready. */
+export const Grow = Game.System(
+ "Town/Grow",
+ {
+ queries: {
+ trees: Game.Query({ selection: { tree: Game.Query.write(Tree) } }),
+ fields: Game.Query({ selection: { field: Game.Query.write(Field) } })
+ }
+ },
+ ({ queries }) => {
+ for (const { data } of queries.trees.each()) {
+ const growth = data.tree.get().growth
+ if (growth < GROWN.tree) data.tree.set({ growth: growth + 1 })
+ }
+ for (const { data } of queries.fields.each()) {
+ const growth = data.field.get().growth
+ if (growth < GROWN.field) data.field.set({ growth: growth + 1 })
+ }
+ }
+)
diff --git a/src/systems.ts b/src/systems.ts
deleted file mode 100644
index 1721fa2..0000000
--- a/src/systems.ts
+++ /dev/null
@@ -1,675 +0,0 @@
-/**
- * The yard's systems: the player's intents become factories and belts,
- * factories work through their jobs, crates ride the belts, and the views
- * follow.
- */
-import { RenderSync } from "@typeonce/bevy-ts-render"
-
-import { BELT_SPEED, BeltView, CrateView, drawBeltBase, drawBeltHatch, drawBeltRails, drawBuilding, drawPlate, drawPlot, FactoryView, heightOf } from "./art.ts"
-import { FOOTPRINT, TILE_H, TILE_W, U, inside, toGrid, toScreen, type Point } from "./iso.ts"
-import { kinds, insetOf, nameFor, awningFor, type KindId } from "./kinds.ts"
-import { key, lengthOf, pointAt, route, type Usage, type Yard } from "./route.ts"
-import {
- Belt, BeltNodes, Clock, Counters, Crate, CrateNodes, DeltaTime, Elapsed, Factory, FactoryNodes, Game,
- Flow, StageService, Totals, Ui, Work
-} from "./schema.ts"
-import type { BeltValue, FactoryValue, HitBox, Preview, WorkValue } from "./schema.ts"
-
-/** Closest two crates may ride on a belt, in grid cells. */
-const SPACING = 7 * U
-const BUILD_SECONDS = 2.4
-
-const FactoryRead = Game.Query({ selection: { factory: Game.Query.read(Factory), work: Game.Query.read(Work) } })
-const FactoryWrite = Game.Query({ selection: { factory: Game.Query.read(Factory), work: Game.Query.write(Work) } })
-const BeltRead = Game.Query({ selection: { belt: Game.Query.read(Belt) } })
-const CrateRead = Game.Query({ selection: { crate: Game.Query.read(Crate) } })
-const CrateWrite = Game.Query({ selection: { crate: Game.Query.write(Crate) } })
-
-export const AdvanceClock = Game.System(
- "Factory/AdvanceClock",
- {
- resources: { dt: Game.System.writeResource(DeltaTime), elapsed: Game.System.writeResource(Elapsed) },
- services: { clock: Game.System.service(Clock) }
- },
- ({ resources, services }) => {
- resources.dt.set(services.clock.deltaSeconds)
- resources.elapsed.update((t) => t + services.clock.deltaSeconds)
- }
-)
-
-// ── Placing and connecting ────────────────────────────────────────────────
-
-/** Moves a belt's ends from the plates' edges in to the buildings' walls. */
-const toWalls = (points: ReadonlyArray<Point>, fromInset: number, toInset: number | null): Array<Point> => {
- const out = points.map((p) => ({ x: p.x, y: p.y }))
- const reach = (end: { x: number; y: number }, next: Point, inset: number) => {
- const length = Math.hypot(end.x - next.x, end.y - next.y) || 1
- end.x += ((end.x - next.x) / length) * inset
- end.y += ((end.y - next.y) / length) * inset
- }
- if (out.length >= 2) {
- reach(out[0]!, out[1]!, fromInset)
- if (toInset !== null) reach(out[out.length - 1]!, out[out.length - 2]!, toInset)
- }
- return out
-}
-
-interface Placed {
- readonly id: number
- readonly kind: KindId
- readonly x: number
- readonly y: number
-}
-
-/** What stands where, kept up to date while one tick's intents are applied. */
-class Occupancy implements Yard {
- readonly factories = new Map<number, Placed>()
- readonly cells = new Map<number, number>()
- readonly uses = new Map<number, Usage>()
- readonly beltCells = new Map<number, Array<number>>()
- readonly belts = new Map<number, BeltValue>()
-
- addFactory(f: Placed) {
- this.factories.set(f.id, f)
- for (let dx = 0; dx < FOOTPRINT; dx++) for (let dy = 0; dy < FOOTPRINT; dy++) this.cells.set(key(f.x + dx, f.y + dy), f.id)
- }
-
- addBelt(b: BeltValue) {
- this.belts.set(b.id, b)
- b.cells.forEach((c, i) => {
- const k = key(c.x, c.y)
- const u = this.uses.get(k) ?? { h: false, v: false, turn: false }
- const use = b.uses[i]!
- if (use === "turn") u.turn = true
- else u[use] = true
- this.uses.set(k, u)
- this.beltCells.set(k, [...(this.beltCells.get(k) ?? []), b.id])
- })
- }
-
- blocked = (x: number, y: number) => this.cells.has(key(x, y))
- usage = (x: number, y: number) => this.uses.get(key(x, y))
-
- canPlace(x: number, y: number) {
- for (let dx = 0; dx < FOOTPRINT; dx++) {
- for (let dy = 0; dy < FOOTPRINT; dy++) {
- const cx = x + dx
- const cy = y + dy
- if (!inside(cx, cy) || this.cells.has(key(cx, cy)) || this.uses.has(key(cx, cy))) return false
- }
- }
- return true
- }
-}
-
-/** A building's hit area: its plate, or its walls and roof as drawn. */
-const hitBox = (f: FactoryValue): HitBox => {
- const kind = kinds[f.kind]
- const centre = toScreen(f.x + FOOTPRINT / 2, f.y + FOOTPRINT / 2)
- const a = kind.half * U
- const top = centre.y - a * TILE_H - heightOf(kind) - 26
- return {
- id: f.id,
- depth: f.x + f.y + FOOTPRINT,
- contains: (at) => {
- const g = toGrid(at.x, at.y)
- if (g.x >= f.x && g.x <= f.x + FOOTPRINT && g.y >= f.y && g.y <= f.y + FOOTPRINT) return true
- return Math.abs(at.x - centre.x) <= a * TILE_W && at.y >= top && at.y <= centre.y
- }
- }
-}
-
-const factoryAt = (hits: ReadonlyArray<HitBox>, at: Point): number | null => hits.find((h) => h.contains(at))?.id ?? null
-
-/** The footprint centred on a point, by its top cell. */
-const footprintAt = (at: Point): Point => {
- const g = toGrid(at.x, at.y)
- return { x: Math.floor(g.x - (FOOTPRINT - 1) / 2), y: Math.floor(g.y - (FOOTPRINT - 1) / 2) }
-}
-
-const cellAt = (at: Point): Point => {
- const g = toGrid(at.x, at.y)
- return { x: Math.floor(g.x), y: Math.floor(g.y) }
-}
-
-const emptyPreview = (): Preview => ({ ghost: null, plots: [], path: null, hoverFactory: null, hoverBelt: null, focus: null, danger: false, tooltip: null })
-
-export const Interact = Game.System(
- "Factory/Interact",
- {
- queries: { factories: FactoryRead, belts: BeltRead, crates: CrateRead },
- resources: { counters: Game.System.writeResource(Counters), totals: Game.System.readResource(Totals), flow: Game.System.readResource(Flow) },
- services: { ui: Game.System.service(Ui) }
- },
- ({ queries, resources, services, commands }) => {
- const ui = services.ui
- let yard = new Occupancy()
- const entities = { factories: new Map<number, unknown>(), belts: new Map<number, unknown>() }
- const works = new Map<number, WorkValue>()
- const names = new Map<number, FactoryValue>()
- for (const { entity, data } of queries.factories.each()) {
- const f = data.factory.get()
- yard.addFactory(f)
- entities.factories.set(f.id, entity.id)
- works.set(f.id, data.work.get())
- names.set(f.id, f)
- }
- for (const { entity, data } of queries.belts.each()) {
- const b = data.belt.get()
- yard.addBelt(b)
- entities.belts.set(b.id, entity.id)
- }
- let hits: Array<HitBox> = [...names.values()].map(hitBox).sort((l, r) => r.depth - l.depth)
-
- const despawnBelt = (id: number) => {
- const entity = entities.belts.get(id)
- if (entity === undefined) return
- commands.despawn(entity as never)
- for (const crate of queries.crates.each()) if (crate.data.crate.get().belt === id) commands.despawn(crate.entity.id)
- entities.belts.delete(id)
- }
-
- const removeFactory = (factory: number) => {
- const entity = entities.factories.get(factory)
- if (entity !== undefined) commands.despawn(entity as never)
- for (const b of yard.belts.values()) if (b.from === factory || b.to === factory) despawnBelt(b.id)
- if (ui.selected === factory) ui.selected = null
- }
-
- const remove = (at: Point) => {
- const factory = factoryAt(hits, at)
- if (factory !== null) return removeFactory(factory)
- const cell = cellAt(at)
- const belt = inside(cell.x, cell.y) ? yard.beltCells.get(key(cell.x, cell.y))?.at(-1) : undefined
- if (belt !== undefined) despawnBelt(belt)
- }
-
- /** Places a factory, returning its id (or `null` when there is no room). */
- const place = (kind: KindId, cell: Point): number | null => {
- if (!yard.canPlace(cell.x, cell.y)) {
- ui.toast("No room there")
- return null
- }
- const { nextId, placed } = resources.counters.get()
- const factory: FactoryValue = { id: nextId, kind, name: nameFor(placed), color: awningFor(placed), x: cell.x, y: cell.y }
- const work: WorkValue = { status: "building", built: 0, progress: 0, inputs: 0, outputs: 0, shipped: 0, made: 0, turn: 0, pulse: 0 }
- commands.spawn(Game.Command.spawn([Factory, factory], [Work, work]))
- resources.counters.set({ nextId: nextId + 1, placed: placed + 1 })
- yard.addFactory(factory)
- names.set(factory.id, factory)
- works.set(factory.id, work)
- hits = [...names.values()].map(hitBox).sort((l, r) => r.depth - l.depth)
- return factory.id
- }
-
- const connect = (fromId: number, toId: number) => {
- const from = yard.factories.get(fromId)
- const to = yard.factories.get(toId)
- if (!from || !to || fromId === toId) return
- if (kinds[from.kind].makes === 0) return ui.toast("A depot only takes crates in")
- if (kinds[to.kind].needs === 0) return ui.toast("A source takes nothing in")
- for (const b of yard.belts.values()) if (b.from === fromId && b.to === toId) return ui.toast("Already connected")
- const found = route(yard, from, to)
- if (!found) return ui.toast("No room for a belt")
- const { nextId } = resources.counters.get()
- const points = toWalls(found.points, insetOf(kinds[from.kind]), insetOf(kinds[to.kind]))
- const belt: BeltValue = { id: nextId, from: fromId, to: toId, cells: found.cells, uses: found.uses, points, length: lengthOf(points) }
- commands.spawn(Game.Command.spawn([Belt, belt]))
- resources.counters.update((c) => ({ ...c, nextId: c.nextId + 1 }))
- yard.addBelt(belt)
- }
-
- /** A plot's top cell lies wholly inside the yard. */
- const onYard = (cell: Point) => inside(cell.x, cell.y) && inside(cell.x + FOOTPRINT - 1, cell.y + FOOTPRINT - 1)
-
- for (const intent of ui.intents.splice(0)) {
- switch (intent.type) {
- case "place":
- place(intent.kind, intent.cell)
- break
- case "build": {
- if (!ui.plot) break
- const id = place(intent.kind, ui.plot)
- if (id !== null) {
- ui.plot = null
- ui.plotKind = null
- ui.selected = id
- }
- break
- }
- case "remove":
- removeFactory(intent.factory)
- break
- case "link": {
- const at = (cell: Point) => yard.cells.get(key(cell.x, cell.y))
- const from = at(intent.from)
- const to = at(intent.to)
- if (from !== undefined && to !== undefined) connect(from, to)
- break
- }
- case "clear":
- for (const entity of entities.factories.values()) commands.despawn(entity as never)
- for (const id of [...entities.belts.keys()]) despawnBelt(id)
- for (const crate of queries.crates.each()) commands.despawn(crate.entity.id)
- resources.counters.update((c) => ({ ...c, placed: 0 }))
- yard = new Occupancy()
- names.clear()
- hits = []
- ui.selected = null
- ui.dragFrom = null
- ui.linkFrom = null
- ui.plot = null
- break
- case "press":
- ui.dragFrom = ui.mode === "select" && ui.linkFrom === null ? factoryAt(hits, intent.at) : null
- break
- case "release": {
- if (ui.mode === "bulldoze") {
- if (!intent.panned) remove(intent.at)
- break
- }
- const target = factoryAt(hits, intent.at)
- if (ui.dragFrom !== null && target !== null && target !== ui.dragFrom) {
- // Dragged from one factory to another: a belt between them.
- connect(ui.dragFrom, target)
- ui.selected = ui.dragFrom
- ui.plot = null
- } else if (ui.linkFrom !== null) {
- if (!intent.panned) {
- if (target !== null && target !== ui.linkFrom) connect(ui.linkFrom, target)
- ui.linkFrom = null
- }
- } else if (target !== null && target === ui.dragFrom) {
- ui.selected = target
- ui.plot = null
- } else if (!intent.panned) {
- // A tap on the ground picks the plot there (or closes the panel off the yard).
- const cell = footprintAt(intent.at)
- ui.selected = null
- ui.plot = onYard(cell) ? cell : null
- ui.plotKind = null
- }
- ui.dragFrom = null
- break
- }
- }
- }
- if (ui.selected !== null && !yard.factories.has(ui.selected)) ui.selected = null
- if (ui.linkFrom !== null && !yard.factories.has(ui.linkFrom)) ui.linkFrom = null
-
- // What the pointer is over, and what that brings into focus.
- ui.hits = hits
- const preview = emptyPreview()
- const pointer = ui.pointer
- if (pointer) {
- preview.hoverFactory = factoryAt(hits, pointer)
- const cell = cellAt(pointer)
- preview.hoverBelt = preview.hoverFactory === null && inside(cell.x, cell.y) ? yard.beltCells.get(key(cell.x, cell.y))?.at(-1) ?? null : null
- }
-
- const around = (id: number) => {
- const factories = new Set([id])
- const belts = new Set<number>()
- for (const b of yard.belts.values()) {
- if (b.from === id || b.to === id) {
- belts.add(b.id)
- factories.add(b.from)
- factories.add(b.to)
- }
- }
- return { factories, belts }
- }
-
- if (ui.plot) {
- const free = yard.canPlace(ui.plot.x, ui.plot.y)
- preview.plots.push({ ...ui.plot, look: free ? "picked" : "blocked" })
- if (ui.plotKind) preview.ghost = { kind: ui.plotKind, cell: ui.plot, valid: free }
- }
-
- if (ui.mode === "bulldoze") {
- preview.danger = true
- if (preview.hoverFactory !== null) preview.focus = around(preview.hoverFactory)
- else if (preview.hoverBelt !== null) {
- const b = yard.belts.get(preview.hoverBelt)!
- preview.focus = { factories: new Set([b.from, b.to]), belts: new Set([b.id]) }
- }
- } else {
- const from = ui.dragFrom ?? ui.linkFrom
- const source = from !== null ? yard.factories.get(from) : undefined
- if (source && pointer && preview.hoverFactory !== from) {
- const target = preview.hoverFactory !== null ? yard.factories.get(preview.hoverFactory) : undefined
- const cell = cellAt(pointer)
- const found = target ? route(yard, source, target) : inside(cell.x, cell.y) ? route(yard, source, { cell }) : null
- const allowed = target !== undefined && kinds[source.kind].makes > 0 && kinds[target.kind].needs > 0
- if (found) {
- preview.path = {
- points: toWalls(found.points, insetOf(kinds[source.kind]), target ? insetOf(kinds[target.kind]) : null),
- valid: allowed
- }
- }
- }
- // The plot under the pointer, when a tap there would pick it.
- if (pointer && from === null && preview.hoverFactory === null) {
- const cell = footprintAt(pointer)
- const picked = ui.plot && ui.plot.x === cell.x && ui.plot.y === cell.y
- if (onYard(cell) && !picked) preview.plots.unshift({ ...cell, look: "hover" })
- }
- const focusOn = from ?? preview.hoverFactory ?? ui.selected
- if (focusOn !== null) {
- const focus = around(focusOn)
- if (preview.hoverFactory !== null) focus.factories.add(preview.hoverFactory)
- preview.focus = focus
- }
- }
-
- const shown = preview.hoverFactory
- const f = shown !== null ? names.get(shown) : undefined
- const w = shown !== null ? works.get(shown) : undefined
- if (f && w) {
- const kind = kinds[f.kind]
- const stock = kind.makes === 0 ? `${w.shipped} shipped` : kind.needs === 0 ? `${w.outputs} ready` : `${w.inputs} in · ${w.outputs} out`
- preview.tooltip = `${kind.title.toLowerCase()}/${f.name} ${w.status} · ${stock}`
- } else if (preview.hoverBelt !== null) {
- const b = yard.belts.get(preview.hoverBelt)!
- preview.tooltip = `belt ${names.get(b.from)?.name ?? "?"} → ${names.get(b.to)?.name ?? "?"} ${resources.flow.get()[b.id] ?? 0} crates`
- }
- ui.preview = preview
-
- // The side panel: the picked factory, or the picked plot.
- const flow = resources.flow.get()
- const link = (id: number, belt: number) => {
- const other = names.get(id)!
- return { id, name: other.name, kind: other.kind, crates: flow[belt] ?? 0 }
- }
- const picked = ui.selected !== null ? names.get(ui.selected) : undefined
- const pickedWork = ui.selected !== null ? works.get(ui.selected) : undefined
- if (picked && pickedWork) {
- const belts = [...yard.belts.values()]
- ui.panel = {
- type: "factory",
- id: picked.id,
- name: picked.name,
- kind: picked.kind,
- status: pickedWork.status,
- inputs: pickedWork.inputs,
- outputs: pickedWork.outputs,
- made: picked.kind === "depot" ? pickedWork.shipped : pickedWork.made,
- takes: belts.filter((b) => b.to === picked.id).map((b) => link(b.from, b.id)),
- feeds: belts.filter((b) => b.from === picked.id).map((b) => link(b.to, b.id)),
- linking: ui.linkFrom === picked.id
- }
- } else if (ui.plot) {
- const { x, y } = ui.plot
- let reason = `${FOOTPRINT} × ${FOOTPRINT} cells, free to build on`
- for (let dx = 0; dx < FOOTPRINT; dx++) {
- for (let dy = 0; dy < FOOTPRINT; dy++) {
- if (yard.cells.has(key(x + dx, y + dy))) reason = "a factory stands here"
- else if (yard.uses.has(key(x + dx, y + dy)) && reason.endsWith("on")) reason = "a belt runs across it"
- }
- }
- ui.panel = { type: "plot", x, y, free: yard.canPlace(x, y), reason }
- } else ui.panel = null
-
- const centres = new Map<number, Point>()
- for (const f of names.values()) centres.set(f.id, toScreen(f.x + FOOTPRINT / 2, f.y + FOOTPRINT / 2))
- ui.centres = centres
-
- let crates = 0
- for (const _ of queries.crates.each()) crates++
- ui.stats = { factories: yard.factories.size, belts: yard.belts.size, crates, shipped: resources.totals.get().shipped }
- }
-)
-
-// ── Work ──────────────────────────────────────────────────────────────────
-
-export const RunFactories = Game.System(
- "Factory/RunFactories",
- {
- queries: { factories: FactoryWrite, belts: BeltRead, crates: CrateRead },
- resources: { dt: Game.System.readResource(DeltaTime), totals: Game.System.writeResource(Totals) }
- },
- ({ queries, resources, commands }) => {
- const dt = resources.dt.get()
- const outgoing = new Map<number, Array<BeltValue>>()
- const incoming = new Set<number>()
- for (const { data } of queries.belts.each()) {
- const b = data.belt.get()
- outgoing.set(b.from, [...(outgoing.get(b.from) ?? []), b])
- incoming.add(b.to)
- }
- // A belt takes a new crate once the last one has moved off its start.
- const nearest = new Map<number, number>()
- for (const { data } of queries.crates.each()) {
- const c = data.crate.get()
- nearest.set(c.belt, Math.min(nearest.get(c.belt) ?? Infinity, c.distance))
- }
-
- for (const { data } of queries.factories.each()) {
- const f = data.factory.get()
- const kind = kinds[f.kind]
- const w = { ...data.work.get() }
- w.pulse = Math.max(0, w.pulse - dt * 3)
- if (w.built < 1) {
- w.built = Math.min(1, w.built + dt / BUILD_SECONDS)
- w.status = "building"
- data.work.set(w)
- continue
- }
- const outs = outgoing.get(f.id) ?? []
- const fed = incoming.has(f.id)
-
- if (w.progress === 0 && w.inputs >= kind.needs && w.outputs + kind.makes <= kind.outputCap && (kind.makes > 0 || w.inputs > 0)) {
- w.inputs -= kind.needs
- w.progress = 1e-6
- }
- if (w.progress > 0) {
- w.progress += dt / kind.period
- if (w.progress >= 1) {
- w.progress = 0
- w.outputs += kind.makes
- w.made += 1
- w.pulse = 1
- if (kind.makes === 0) {
- w.shipped += 1
- resources.totals.update((t) => ({ shipped: t.shipped + 1 }))
- }
- }
- }
-
- // Send one crate a tick down the next belt with room at its start.
- if (w.outputs > 0) {
- for (let i = 0; i < outs.length; i++) {
- const belt = outs[(w.turn + i) % outs.length]!
- if ((nearest.get(belt.id) ?? Infinity) < SPACING) continue
- const start = belt.points[0]!
- commands.spawn(Game.Command.spawn([Crate, { belt: belt.id, distance: 0, color: f.color, x: start.x, y: start.y }]))
- nearest.set(belt.id, 0)
- w.outputs -= 1
- w.turn = (w.turn + i + 1) % outs.length
- break
- }
- }
-
- w.status = w.progress > 0
- ? "working"
- : w.outputs + kind.makes > kind.outputCap && kind.makes > 0
- ? outs.length > 0 ? "blocked" : "idle"
- : w.inputs < Math.max(1, kind.needs)
- ? fed ? "starved" : "idle"
- : "working"
- data.work.set(w)
- }
- }
-)
-
-export const MoveCrates = Game.System(
- "Factory/MoveCrates",
- {
- queries: { crates: CrateWrite, belts: BeltRead, factories: FactoryWrite },
- resources: { dt: Game.System.readResource(DeltaTime), flow: Game.System.writeResource(Flow) }
- },
- ({ queries, resources, commands }) => {
- const step = BELT_SPEED * resources.dt.get()
- const belts = new Map<number, BeltValue>()
- for (const { data } of queries.belts.each()) belts.set(data.belt.get().id, data.belt.get())
- const targets = new Map<number, { readonly cap: number; readonly ready: boolean; inputs: number; set: (inputs: number) => void }>()
- for (const { data } of queries.factories.each()) {
- const f = data.factory.get()
- const w = data.work.get()
- targets.set(f.id, {
- cap: kinds[f.kind].inputCap,
- ready: w.built >= 1,
- inputs: w.inputs,
- set: (inputs) => data.work.set({ ...data.work.get(), inputs })
- })
- }
-
- const rows = [...queries.crates.each()]
- const riding = new Map<number, typeof rows>()
- for (const row of rows) {
- const belt = row.data.crate.get().belt
- if (!belts.has(belt)) commands.despawn(row.entity.id)
- else riding.set(belt, [...(riding.get(belt) ?? []), row])
- }
-
- for (const [id, crates] of riding) {
- const belt = belts.get(id)!
- const target = targets.get(belt.to)
- crates.sort((l, r) => r.data.crate.get().distance - l.data.crate.get().distance)
- let limit = belt.length
- for (const row of crates) {
- const c = row.data.crate.get()
- const distance = Math.max(c.distance, Math.min(c.distance + step, limit))
- // At the end of the belt, the crate goes in if the building has room.
- if (distance >= belt.length - 1e-6 && target && target.ready && target.inputs < target.cap) {
- target.inputs += 1
- target.set(target.inputs)
- resources.flow.update((flow) => ({ ...flow, [id]: (flow[id] ?? 0) + 1 }))
- commands.despawn(row.entity.id)
- continue
- }
- if (distance !== c.distance) {
- const p = pointAt(belt.points, distance)
- row.data.crate.set({ ...c, distance, x: p.x, y: p.y })
- }
- limit = distance - SPACING
- }
- }
- }
-)
-
-// ── Views ─────────────────────────────────────────────────────────────────
-
-export const RenderFactories = RenderSync.system(Game, {
- name: "Factory/RenderFactories",
- renderable: Factory,
- registry: FactoryNodes,
- services: { stage: StageService },
- create: ({ renderable, services }) => new FactoryView(renderable.kind, renderable.name, renderable.color, services.stage),
- apply: (node, { renderable }) => node.place(renderable.x, renderable.y)
-})
-
-export const RenderBelts = RenderSync.system(Game, {
- name: "Factory/RenderBelts",
- renderable: Belt,
- registry: BeltNodes,
- create: ({ renderable }) => new BeltView(renderable.points),
- apply: () => {}
-})
-
-export const RenderCrates = RenderSync.system(Game, {
- name: "Factory/RenderCrates",
- renderable: Crate,
- transform: Crate,
- registry: CrateNodes,
- create: ({ renderable }) => new CrateView(renderable.color),
- apply: (node, { transform }) => node.place(transform.x, transform.y)
-})
-
-type Emphasis = "normal" | "dim" | "focus" | "danger"
-
-export const Animate = Game.System(
- "Factory/Animate",
- {
- queries: { factories: FactoryRead, belts: BeltRead, crates: CrateRead },
- resources: { dt: Game.System.readResource(DeltaTime), elapsed: Game.System.readResource(Elapsed) },
- services: { ui: Game.System.service(Ui), factoryNodes: Game.System.service(FactoryNodes), beltNodes: Game.System.service(BeltNodes), crateNodes: Game.System.service(CrateNodes) }
- },
- ({ queries, resources, services }) => {
- const { focus, danger } = services.ui.preview
- const emphasis = (inFocus: boolean): Emphasis => (focus === null ? "normal" : !inFocus ? "dim" : danger ? "danger" : "focus")
- const dt = resources.dt.get()
- // A factory gets a door on its left wall when a belt meets it there (its +y side).
- const leftDoors = new Set<number>()
- const centres = new Map<number, Point>()
- for (const { data } of queries.factories.each()) {
- const f = data.factory.get()
- centres.set(f.id, { x: f.x + FOOTPRINT / 2, y: f.y + FOOTPRINT / 2 })
- }
- for (const { data } of queries.belts.each()) {
- const b = data.belt.get()
- const ends: ReadonlyArray<readonly [number, Point]> = [[b.from, b.points[0]!], [b.to, b.points[b.points.length - 1]!]]
- for (const [id, end] of ends) {
- const c = centres.get(id)
- if (c && end.y - c.y > Math.abs(end.x - c.x)) leftDoors.add(id)
- }
- }
- for (const { entity, data } of queries.factories.each()) {
- const f = data.factory.get()
- services.factoryNodes.get(entity.id as never)?.update(data.work.get(), dt, emphasis(focus?.factories.has(f.id) ?? true), leftDoors.has(f.id))
- }
- for (const { entity, data } of queries.belts.each()) {
- services.beltNodes.get(entity.id as never)?.update(resources.elapsed.get(), emphasis(focus?.belts.has(data.belt.get().id) ?? true))
- }
- for (const { entity, data } of queries.crates.each()) {
- const node = services.crateNodes.get(entity.id as never)
- if (node) node.alpha = focus === null || focus.belts.has(data.crate.get().belt) ? 1 : 0.25
- }
- }
-)
-
-/** The ghost of the building being placed, and the belt being dragged. */
-export const DrawPreview = Game.System(
- "Factory/DrawPreview",
- {
- resources: { elapsed: Game.System.readResource(Elapsed) },
- services: { ui: Game.System.service(Ui), stage: Game.System.service(StageService) }
- },
- ({ resources, services }) => {
- const { ghost, path } = services.ui.preview
- const { overlay, ghost: shadow } = services.stage
- overlay.clear()
- shadow.clear()
- for (const plot of services.ui.preview.plots) drawPlot(overlay, plot.x, plot.y, plot.look, resources.elapsed.get())
- if (ghost) {
- const kind = kinds[ghost.kind]
- const centre = toScreen(ghost.cell.x + FOOTPRINT / 2, ghost.cell.y + FOOTPRINT / 2)
- shadow.position.set(centre.x, centre.y)
- shadow.zIndex = ghost.cell.x + ghost.cell.y + FOOTPRINT
- drawBuilding(shadow, kind, 0xb9beb5, 1, 0, 0)
- shadow.alpha = ghost.valid ? 0.45 : 0.25
- shadow.tint = ghost.valid ? 0xffffff : 0xf3b5aa
- }
- if (path && path.points.length >= 2) {
- drawBeltBase(overlay, path.points, 0.7)
- drawBeltHatch(overlay, path.points, resources.elapsed.get() * BELT_SPEED, 0.6)
- drawBeltRails(overlay, path.points, path.valid ? 0.9 : 0.45, path.valid ? 0x3d4943 : 0x8f9891)
- }
- }
-)
-
-export const setup = Game.Schedule(Interact, Game.Schedule.applyDeferred(), RenderFactories, RenderBelts)
-
-export const update = Game.Schedule(
- AdvanceClock,
- Interact,
- RunFactories,
- Game.Schedule.applyDeferred(),
- MoveCrates,
- Game.Schedule.applyDeferred(),
- RenderFactories,
- RenderBelts,
- RenderCrates,
- Animate,
- DrawPreview
-)
diff --git a/src/ui.ts b/src/ui.ts
new file mode 100644
index 0000000..69e93df
--- /dev/null
+++ b/src/ui.ts
@@ -0,0 +1,122 @@
+/**
+ * The bridge between the page and the town. The page writes the pointer and
+ * gestures; the town's present systems turn gestures into a selection, a
+ * preview, and edits; the simulation applies the edits on its next step.
+ * None of it is saved: it is host state, handed to systems as a service.
+ */
+import type { Amounts, GoodId, KindId, Tier } from "./content.ts"
+import type { Point } from "./iso.ts"
+import type { Status } from "./schema.ts"
+
+export type Tool = "select" | "road" | "home" | "bulldoze" | "place"
+
+/** A change to the town, applied by the simulation (see `ApplyEdits`). */
+export type Edit =
+ /** `open`: show the new building in the panel. */
+ | { readonly type: "building"; readonly kind: KindId; readonly cell: Point; readonly open: boolean }
+ | { readonly type: "homes"; readonly cells: ReadonlyArray<Point> }
+ | { readonly type: "roads"; readonly cells: ReadonlyArray<Point> }
+ /** Removes whatever stands on a cell (not rocks, water, or the town hall). */
+ | { readonly type: "remove"; readonly cell: Point }
+ /** Sets a tier's tax rate, in percent of the usual. */
+ | { readonly type: "tax"; readonly tier: "settlers" | "citizens"; readonly rate: number }
+ /** Sells a good to traders, or stops selling it. */
+ | { readonly type: "sell"; readonly good: GoodId; readonly on: boolean }
+ /** How much of each good the town keeps before selling. */
+ | { readonly type: "reserve"; readonly amount: number }
+ /** Clears everything and founds a new town on land grown from `seed`. */
+ | { readonly type: "newTown"; readonly seed: number }
+
+/** What the pointer did, in world pixels. */
+export type Gesture =
+ | { readonly type: "press"; readonly at: Point }
+ | { readonly type: "release"; readonly at: Point; readonly panned: boolean }
+
+export type Look = "hover" | "picked" | "blocked" | "reach"
+
+/** What the town shows besides its entities: ghosts, the road being dragged, outlines. */
+export interface Preview {
+ /** Outlines on the floor: `size` cells a side from (x, y). */
+ plots: Array<{ readonly x: number; readonly y: number; readonly size: number; readonly look: Look }>
+ /** Ghost buildings and homes, at their footprints' top cells. */
+ ghosts: Array<{ readonly what: KindId | "home"; readonly cell: Point }>
+ /** Road cells about to be laid. */
+ roads: Array<Point>
+ /** The entity under the pointer. */
+ hover: number | null
+ /** Bulldozing: the hovered thing is tinted. */
+ danger: boolean
+ tooltip: string | null
+}
+
+export const emptyPreview = (): Preview => ({ plots: [], ghosts: [], roads: [], hover: null, danger: false, tooltip: null })
+
+/** The side panel: the build menu, the town's numbers and taxes, a building, or a home. */
+export type Panel =
+ | { readonly type: "build" }
+ | { readonly type: "town" }
+ | {
+ readonly type: "building"
+ readonly id: number
+ readonly cell: Point
+ readonly kind: KindId
+ readonly status: Status
+ /** Why it is not working, when it is not. */
+ readonly problem: string | null
+ readonly lines: ReadonlyArray<string>
+ }
+ | {
+ readonly type: "house"
+ readonly id: number
+ readonly cell: Point
+ readonly tier: Tier
+ readonly lines: ReadonlyArray<string>
+ }
+
+/** A thing's hit area for the pointer, nearest first. */
+export interface HitBox {
+ readonly id: number
+ readonly depth: number
+ readonly contains: (at: Point) => boolean
+}
+
+/** The town's numbers for the top bar. */
+export interface Stats {
+ readonly coins: number
+ readonly taxes: number
+ readonly trade: number
+ readonly upkeep: number
+ /** Coins a minute: taxes less upkeep. */
+ readonly net: number
+ readonly homes: number
+ /** Homes with each need met. */
+ readonly needs: { readonly food: number; readonly bread: number; readonly cloth: number; readonly faith: number }
+ readonly policy: { readonly settlers: number; readonly citizens: number; readonly sells: ReadonlyArray<GoodId>; readonly reserve: number }
+ readonly stock: Amounts
+ readonly settlers: number
+ readonly citizens: number
+ readonly jobs: number
+ readonly employed: number
+}
+
+export interface UiValue {
+ tool: Tool
+ /** The kind being placed with the `place` tool. */
+ placing: KindId | null
+ /** Which side panel the toolbar opened, when nothing is selected. */
+ menu: "build" | "town" | null
+ /** The pointer in world pixels, or `null` off the canvas. */
+ pointer: Point | null
+ /** Where a road or a row of homes being dragged started. */
+ dragFrom: Point | null
+ selected: number | null
+ gestures: Array<Gesture>
+ edits: Array<Edit>
+ preview: Preview
+ hits: ReadonlyArray<HitBox>
+ panel: Panel | null
+ /** Where each building and home stands (world pixels), for the camera to look at. */
+ centres: ReadonlyMap<number, Point>
+ stats: Stats | null
+ toast: (message: string) => void
+}
diff --git a/tsconfig.json b/tsconfig.json
index 77a112d..a61cfc8 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,5 +1,5 @@
{
- "include": ["src/**/*.ts", "vite.config.ts"],
+ "include": ["src/**/*.ts", "scripts/**/*.ts", "vite.config.ts"],
"compilerOptions": {
"noEmit": true,
"target": "ES2022",