Skip to content

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

Upgrades you can see and choose: an upgrades menu, scaffolding, and works carriers supply

Claudebade4025cdf8
diff --git a/.gitignore b/.gitignore
index cb767f7..5bc2ba9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,4 @@ output/inkline-3d/
output/balance-model/
output/balance-rules/
output/mobile-review/
+output/upgrades/
diff --git a/README.md b/README.md
index 6149d00..c83ff01 100644
--- a/README.md
+++ b/README.md
@@ -98,9 +98,11 @@ A town is founded as a hamlet. Hold every goal of the next rank for two
minutes (enough people and coins, a share of them citizens, a town that
approves of you) and it rises to a **village**, then a **town**, then a
**city**, whose finest streets must hold burghers in townhouses. Each rank
-brings a reward from the crown, and a town can upgrade its market to a
-market hall and its chapel to a church. Nothing ends when a rank is
-reached.
+brings a reward from the crown and opens upgrades made where buildings
+stand: the town hall becomes a guildhall and then a city hall, the market
+a market hall, the bakery an ovenworks, the quarry a masonry, and more,
+with scaffolding rising while carriers bring their materials. Nothing ends
+when a rank is reached.
Three minutes in debt, two minutes of uproar, a town that empties out, or
three of the crown's requests ignored, and the term is **lost**. Otherwise
diff --git a/docs/how-to-play.md b/docs/how-to-play.md
index 2a88deb..bb76654 100644
--- a/docs/how-to-play.md
+++ b/docs/how-to-play.md
@@ -92,11 +92,25 @@ six months.
townhouses). Hold every goal of the next rank for two minutes and the town
rises: the crown sends a reward, and play goes on. A rank is never lost.
The town panel shows the next rank's goals.
-- **Upgrades**: a town can turn its market into a *market hall*, and its
- chapel into a *church*, where they stand (the building's panel):
- paid at once in coins, planks, stone, and tools, the walker goes further
- and more often, the street around it is finer, and the upkeep is higher.
- Pulling one down gives back part of what both cost.
+- **Upgrades** are made where a building stands, so they need no more
+ land. The build menu's *upgrades* lists every one, what it gives and
+ what it costs: pick one and the buildings it can go to are outlined;
+ hover one to see the same, and click it to begin (or use the button in
+ its panel). The coins are paid when the works begin; carriers then
+ bring the planks, stone, and tools, builders work them in as they come,
+ and scaffolding rises inside its plot. It goes on working meanwhile.
+ - a village: the town hall becomes a *guildhall* (holds twice as much,
+ more carriers, a longer walk, a tenth less administration), and a
+ warehouse a *depot* (holds 120, two more carriers);
+ - a town: the guildhall a *city hall* (a fifth less administration),
+ the market a *market hall*, the chapel a *church*, the bakery an
+ *ovenworks* (bread every 4 s, a third baker), the farm an *estate*
+ (a third hand, half again as fast), the quarry a *masonry* (cuts
+ worked-out rock at full pace), and the fire watch a *fire brigade*
+ (four firefighters, a longer walk).
+ Every upgrade costs more upkeep. None is ever needed: each pays for
+ itself in under an hour of play, in coins or in what it does. Pulling
+ one down gives back part of what all of it cost.
- **The end of a term**: it is *lost* to bankruptcy (three minutes in
debt), revolt (approval at -50 or below for two minutes), abandonment
(people fall below 15% of their peak), or dismissal (three of the crown's
diff --git a/package.json b/package.json
index 0fe18ba..0220e24 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,7 @@
"check:effects": "node scripts/check-house-effects.ts",
"check:revisions": "node scripts/check-model-revisions.ts",
"check:park": "node scripts/check-park.ts",
+ "look:upgrades": "node scripts/look-upgrades.ts",
"test": "node --test \"test/*.test.ts\"",
"release": "pnpm --dir deploy release"
},
diff --git a/scripts/look-upgrades.ts b/scripts/look-upgrades.ts
new file mode 100644
index 0000000..981abc5
--- /dev/null
+++ b/scripts/look-upgrades.ts
@@ -0,0 +1,63 @@
+/**
+ * A look at upgrades in the real 3D game: the build menu's upgrades, the
+ * upgrade tool's tooltip over the town hall, its scaffolding part way, and
+ * the guildhall it becomes. Screenshots go to `output/upgrades`.
+ *
+ * pnpm dev --host 127.0.0.1 --port 5232 &
+ * node scripts/look-upgrades.ts
+ */
+import { chromium } from "playwright"
+import { mkdir } from "node:fs/promises"
+
+const executable = process.env.BROWSER_EXECUTABLE_PATH
+const browser = await chromium.launch({ headless: true, ...(executable ? { executablePath: executable } : {}) })
+const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, deviceScaleFactor: 1 })
+const out = process.env.OUT ?? "output/upgrades"
+await mkdir(out, { recursive: true })
+const errors: Array<string> = []
+page.on("pageerror", (e) => errors.push(e.message))
+try {
+ await page.goto(process.env.GAME_BASE_URL ?? "http://127.0.0.1:5232")
+ await page.waitForFunction(() => (window as any).town)
+ await page.getByRole("button", { name: "small", exact: true }).click()
+ await page.getByRole("button", { name: "Start new", exact: true }).click()
+ await page.waitForFunction(() => !(window as any).town.ui.founding)
+ await page.locator(".toolbar .pause").click()
+ // A town that has reached the town rank, with coins and materials to spare.
+ await page.evaluate(() => {
+ const { runtime } = (window as any).town
+ const s = runtime.snapshot()
+ s.resources["Town/Fate"].rank = 2
+ s.resources["Town/Treasury"].coins = 5000
+ const hall = s.entities.find((e: any) => e.components["Town/TownHall"])
+ hall.components["Town/Inventory"].stock = { ...hall.components["Town/Inventory"].stock, planks: 90, stone: 90, tools: 20 }
+ runtime.restore(s)
+ })
+ await page.evaluate(() => (window as any).town.advance(1))
+ const hall = await page.evaluate(() => (window as any).town.runtime.snapshot().entities.find((e: any) => e.components["Town/TownHall"]).components["Town/Tile"])
+ await page.evaluate(([x, y]) => { const v = (window as any).town.view; v.focus(x, y); v.camera.zoom = 2.2; v.camera.updateProjectionMatrix() }, [hall.x + 1.5, hall.y + 1.5])
+ // The build menu, scrolled to its upgrades.
+ await page.locator(".toolbar button").filter({ hasText: /build/i }).first().click().catch(() => {})
+ await page.waitForTimeout(400)
+ await page.locator(".panel h3, .panel .title, .panel summary").filter({ hasText: /upgrades/i }).first().scrollIntoViewIfNeeded().catch(() => {})
+ await page.waitForTimeout(600)
+ await page.screenshot({ path: `${out}/1-build-menu.png` })
+ // The upgrade tool over the town hall.
+ await page.evaluate(() => { const t = (window as any).town; t.ui.menu = null; t.ui.tool = "upgrade"; t.ui.upgrading = "townhall" })
+ const box = await page.evaluate(([x, y]) => (window as any).town.view.project(x, y, 40), [hall.x + 1.5, hall.y + 1.5])
+ if (box) await page.mouse.move(box.x, box.y)
+ await page.waitForTimeout(300)
+ await page.screenshot({ path: `${out}/2-hover-tooltip.png` })
+ // Begin, then part way.
+ await page.evaluate(([x, y]) => (window as any).town.ui.edits.push({ type: "upgrade", cell: { x, y } }), [hall.x, hall.y])
+ await page.evaluate(() => (window as any).town.advance(50))
+ await page.evaluate(() => { const t = (window as any).town; t.ui.tool = "select"; t.ui.upgrading = null })
+ await page.waitForTimeout(300)
+ await page.screenshot({ path: `${out}/3-scaffolding.png` })
+ await page.evaluate(() => (window as any).town.advance(90))
+ await page.waitForTimeout(300)
+ await page.screenshot({ path: `${out}/4-guildhall.png` })
+ console.log(JSON.stringify({ errors, upgraded: await page.evaluate(() => (window as any).town.runtime.snapshot().entities.find((e: any) => e.components["Town/TownHall"]).components["Town/Upgraded"] ?? null) }))
+} finally {
+ await browser.close()
+}
diff --git a/src/appeal.ts b/src/appeal.ts
index b20d0d9..c3e23b4 100644
--- a/src/appeal.ts
+++ b/src/appeal.ts
@@ -10,7 +10,7 @@ import { shippedRules, type Rules } from "./rules/config.ts"
* shared by the simulation (which keeps the whole grid, see `Appraise`) and
* the page (which explains one cell).
*/
-import { type GroundId, type KindId, type PropId } from "./content.ts"
+import { upgradeAt, type GroundId, type KindId, type PropId } from "./content.ts"
import { cellOf, DIRS, key } from "./grid.ts"
import { GRID, inside, type Point } from "./iso.ts"
@@ -67,9 +67,9 @@ export const buildingSource = (
kind: KindId,
tile: { readonly x: number; readonly y: number; readonly size: number },
rules: Rules = shippedRules,
- upgraded = false
+ level = 0
): AppealSource | null => {
- const up = upgraded ? rules.kinds[kind].upgrade : undefined
+ const up = upgradeAt(rules.kinds[kind], level)
const a = up?.appeal ?? rules.kinds[kind].appeal
const title = up?.title ?? rules.kinds[kind].title
return a ? { ...tile, value: a.value, reach: a.reach, ...(a.full ? { full: a.full } : {}), label: title.toLowerCase(), mode: "sum" } : null
diff --git a/src/art.ts b/src/art.ts
index c123de2..c01bd87 100644
--- a/src/art.ts
+++ b/src/art.ts
@@ -881,8 +881,10 @@ export interface BuildingLook {
readonly site: number | null
/** A map view's colour washed over it, when one is shown. */
readonly tint?: number | undefined
- /** Upgraded where it stands (see `Kind.upgrade`): drawn taller. */
- readonly upgraded?: boolean
+ /** Upgrades it has had where it stands (see `Kind.upgrade`): drawn as its upgrade. */
+ readonly level?: number
+ /** An upgrade under way: the share of its materials in (scaffolding rises with it), else `null`. */
+ readonly works?: number | null
}
/** A building as drawn: its plate on the floor, its body among the other objects, and its problem marker above everything. */
diff --git a/src/asset-lab/upgrade-dress.ts b/src/asset-lab/upgrade-dress.ts
new file mode 100644
index 0000000..278b2b1
--- /dev/null
+++ b/src/asset-lab/upgrade-dress.ts
@@ -0,0 +1,134 @@
+/**
+ * How a building upgraded where it stands is told apart from the one it
+ * was (the market hall and the church have models of their own, see
+ * `service-upgrades.ts`): what the upgrade adds to it, drawn over the
+ * building's own model and never past its plot. A guildhall's clock tower,
+ * a city hall's dome, a depot's hoist, an ovenworks' second chimney, a
+ * masonry's derrick, an estate's dovecote, a fire brigade's bell. And the
+ * scaffolding that stands inside a building's plot while an upgrade is under
+ * way, rising with the share of its materials in.
+ */
+import { U } from "../iso.ts"
+import { kinds, type KindId } from "../content.ts"
+import { Drawing, palette, square, type InkAsset, type Vertex } from "./primitives.ts"
+
+const brick = { top: 0xd99a7e, left: 0xc77d63, right: 0xb5654a }
+const stone = { top: 0xf0f1eb, left: 0xe1e5dc, right: 0xd3d9cf }
+const slate = { face: 0x8f9891, shade: 0x6f7872 }
+const timber = { top: 0xeee2c8, left: 0xdcc9a8, right: 0xc6b18e }
+
+/** A four-sided roof to a point over (u, v). */
+const spire = (d: Drawing, u: number, v: number, a: number, z: number, rise: number, face: number, shade: number) => {
+ const base: Array<Vertex> = square(u, v, a, z)
+ for (let i = 0; i < 4; i++) d.face([base[i]!, base[(i + 1) % 4]!, [u, v, z + rise]], i === 2 || i === 3 ? face : shade)
+}
+
+/** The kinds that can be upgraded and are drawn by dressing their own model (not the market and chapel). */
+export const dressed = ["townhall", "warehouse", "bakery", "quarry", "farm", "firewatch"] as const satisfies ReadonlyArray<KindId>
+export type DressedKind = (typeof dressed)[number]
+export const isDressed = (id: KindId): id is DressedKind => (dressed as ReadonlyArray<KindId>).includes(id)
+
+/** What an upgrade adds, and the height of its highest point (for the marker over it). */
+const dress = (id: DressedKind, level: number, eave: number): { readonly asset: InkAsset; readonly top: number } => {
+ const d = new Drawing(`${id}-upgrade-${level}`, "Upgrade", "")
+ const plot = kinds[id].size * 8 * U
+ switch (id) {
+ case "townhall": {
+ if (level >= 2) {
+ // A city hall: a broad drum and a dome over the old roof.
+ d.box(0, 0, 7 * U, 7 * U, eave, 18, stone.top, stone.left, stone.right)
+ d.cylinder(0, 0, 6 * U, eave + 18, 10, 0xd3d9cf, 0xf0f1eb, 1, 24)
+ d.ellipsoid(0, 0, eave + 28, 6 * U, 6 * U, 14, 0xb8c9d6, 1, 0xdfe8ee, 20)
+ d.cylinder(0, 0, 0.8 * U, eave + 41, 8, 0xb39a61, 0xd5c18b, 0.7, 10)
+ return { asset: d.asset, top: eave + 50 }
+ }
+ // A guildhall: a clock tower on the roof.
+ d.box(0, 0, 5 * U, 5 * U, eave, 26, stone.top, stone.left, stone.right)
+ // A clock face on each side the camera sees.
+ const w = 5.01 * U, c = 2.2 * U, z = eave + 15
+ d.face([[w, -c, z], [w, c, z], [w, c, z + 8], [w, -c, z + 8]], 0xf7f8f4, 1)
+ d.face([[-c, w, z], [c, w, z], [c, w, z + 8], [-c, w, z + 8]], 0xf7f8f4, 1)
+ d.line([[w, 0, z + 4], [w, 0, z + 7]], 1)
+ d.line([[0, w, z + 4], [1.6 * U, w, z + 4]], 1)
+ spire(d, 0, 0, 6 * U, eave + 26, 16, slate.face, slate.shade)
+ return { asset: d.asset, top: eave + 42 }
+ }
+ case "warehouse": {
+ // A depot: a hoist over the yard, and crates stacked on the roof.
+ const c = plot - 2 * U
+ d.line([[c, c, 0], [c, c, eave + 22]], 1.5)
+ d.line([[c, -c, 0], [c, -c, eave + 22]], 1.5)
+ d.line([[c, c, eave + 22], [c, -c, eave + 22]], 1.5)
+ d.line([[c, 0, eave + 22], [c, 0, eave + 8]], 0.8, palette.ink, 0.7)
+ d.crate(c - 0.5 * U, 0, eave + 2, 0x6e8f36, 1.2 * U, 5)
+ for (const [u, v, z] of [[-8 * U, -8 * U, eave], [-5 * U, -8 * U, eave], [-8 * U, -5 * U, eave], [-6.5 * U, -6.5 * U, eave + 5]] as const)
+ d.crate(u, v, z, 0x8a58a8, 1.2 * U, 5)
+ return { asset: d.asset, top: eave + 26 }
+ }
+ case "bakery": {
+ // An ovenworks: a second, taller brick chimney.
+ d.box(-6 * U, 5 * U, 1.8 * U, 1.8 * U, 0, eave + 30, brick.top, brick.left, brick.right)
+ d.box(-6 * U, 5 * U, 2.2 * U, 2.2 * U, eave + 30, 2, brick.top, brick.left, brick.right)
+ return { asset: d.asset, top: eave + 34 }
+ }
+ case "quarry": {
+ // A masonry: a derrick over the pit, and dressed blocks waiting by it.
+ const c = plot - 2.5 * U
+ d.line([[c, c, 0], [c, c, 52]], 2)
+ d.line([[c, c, 50], [-c * 0.4, -c * 0.4, 30]], 1.5)
+ d.line([[c, c, 0], [c - 4 * U, c, 0], [c, c, 30]], 1, palette.ink, 0.8)
+ d.line([[-c * 0.4, -c * 0.4, 30], [-c * 0.4, -c * 0.4, 14]], 0.8, palette.ink, 0.7)
+ for (const [u, v, z] of [[-c, c, 0], [-c + 2.6 * U, c, 0], [-c + 1.3 * U, c, 4]] as const) d.box(u, v, 1.2 * U, 1.2 * U, z, 4, stone.top, stone.left, stone.right, 1)
+ return { asset: d.asset, top: 56 }
+ }
+ case "farm": {
+ // An estate: a dovecote in a corner of the yard, and a hayrick.
+ const c = plot - 3 * U
+ d.box(c, -c, 2.2 * U, 2.2 * U, 0, 22, timber.top, timber.left, timber.right)
+ spire(d, c, -c, 2.8 * U, 22, 10, slate.face, slate.shade)
+ d.ellipsoid(-c, c, 0, 3 * U, 3 * U, 10, 0xe6c85a, 1, 0xf1dc8a, 16)
+ return { asset: d.asset, top: Math.max(eave + 12, 34) }
+ }
+ case "firewatch": {
+ // A fire brigade: a bell frame with its bell over the roof.
+ const z = eave + 26
+ for (const [u, v] of square(0, 0, 2 * U)) d.line([[u, v, z], [u, v, z + 12]], 1.2)
+ spire(d, 0, 0, 2.6 * U, z + 12, 6, 0xc4523f, 0xa8432f)
+ d.ellipsoid(0, 0, z + 4, 1.2 * U, 1.2 * U, 4, 0xb39a61, 1, 0xd5c18b, 12)
+ return { asset: d.asset, top: z + 20 }
+ }
+ }
+}
+
+/** A building's own model with its upgrades drawn on: what it looks like at `level`. */
+export function dressedBuilding(id: DressedKind, level: number, base: InkAsset, eave: number): InkAsset {
+ const extra = dress(id, level, eave).asset
+ return { ...base, id: `${base.id}-${level}`, faces: [...base.faces, ...extra.faces], strokes: [...base.strokes, ...extra.strokes] }
+}
+
+/** The highest point of an upgraded building, for the marker drawn over it. */
+export const dressedTop = (id: DressedKind, level: number, eave: number): number => dress(id, level, eave).top
+
+/**
+ * Scaffolding inside a building's plot while it is upgraded: poles at its
+ * corners, ledgers and boards rising with the `share` of its materials in,
+ * and the crates the carriers have brought stacked by them.
+ */
+export function scaffoldAsset(size: number, height: number, share: number): InkAsset {
+ const d = new Drawing("scaffold", "Scaffolding", ""),
+ s = (size * 8 - 1.2) * U,
+ top = height + 8,
+ rise = Math.max(4, Math.round(top * Math.min(1, share)))
+ for (const [u, v] of square(0, 0, s)) d.line([[u, v, 0], [u, v, top]], 1.2, 0x8a6a45)
+ // A ledger every few feet of what is in, and the boards they carry.
+ for (let z = 6; z <= rise; z += 8) {
+ d.line([...square(0, 0, s, z), [s, s, z]], 1, 0x8a6a45, 0.9)
+ d.line([[s, s, z + 0.2], [s, -s, z + 0.2]], 2.2, 0xd5a86c, 0.85)
+ }
+ // Diagonal braces on the two faces the camera sees most.
+ d.line([[s, s, 0], [s, -s, rise]], 0.8, 0x8a6a45, 0.7)
+ d.line([[s, s, 0], [-s, s, rise]], 0.8, 0x8a6a45, 0.7)
+ const crates = Math.ceil(Math.min(1, share) * 3)
+ for (let i = 0; i < crates; i++) d.crate(s - 1.4 * U, s - (1.4 + i * 2.6) * U, 0, 0x8f9891, 1.1 * U, 4)
+ return d.asset
+}
diff --git a/src/content.ts b/src/content.ts
index ac4d996..b59f252 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -151,24 +151,14 @@ export interface Kind {
readonly keeps?: number
/**
* What it becomes when upgraded where it stands, once the town has reached
- * `rank` (see `ranks`): paid at once from the treasury and the store, as
- * paving is. Its walker, desirability, and upkeep become these.
+ * `rank` (see `ranks`), and (`next`) what that becomes in turn: its coins
+ * paid when the works begin, its materials carried to it while it goes on
+ * working (see `Works`). Whatever an upgrade gives replaces the kind's own.
*/
readonly upgrade?: Upgrade
}
-/** Coins a minute a building of a kind costs, upgraded or not. */
-export const upkeepOf = (kind: Pick<Kind, "upkeep" | "upgrade">, upgraded: boolean): number => (upgraded && kind.upgrade ? kind.upgrade.upkeep : kind.upkeep)
-
-/** What a building of a kind cost all told, its upgrade included: what pulling it down gives part of back. */
-export const builtCost = (kind: Pick<Kind, "cost" | "upgrade">, upgraded: boolean): Kind["cost"] => {
- if (!upgraded || !kind.upgrade) return kind.cost
- const materials: Partial<Record<GoodId, number>> = { ...kind.cost.materials }
- for (const [g, n] of Object.entries(kind.upgrade.cost.materials) as Array<[GoodId, number]>) materials[g] = (materials[g] ?? 0) + n
- return { coins: kind.cost.coins + kind.upgrade.cost.coins, materials }
-}
-
-/** A building upgraded where it stands (see `Kind.upgrade`). */
+/** A building upgraded where it stands (see `Kind.upgrade`): every field but the first five is what changes. */
export interface Upgrade {
readonly title: string
readonly blurb: string
@@ -177,6 +167,73 @@ export interface Upgrade {
readonly upkeep: number
readonly service?: { readonly seconds: number; readonly range: number }
readonly appeal?: { readonly value: number; readonly reach: number; readonly full?: number }
+ /** Workers it takes, and seconds a job (a recipe's). */
+ readonly workers?: number
+ readonly seconds?: number
+ /** What its shelves hold of each good, and the carriers it sends at once. */
+ readonly cap?: number
+ readonly carriers?: number
+ /** Firefighters it sends out at once (a fire watch's). */
+ readonly crews?: number
+ /** It cuts worked faces at full pace, not a third of it (a quarry's). */
+ readonly deep?: boolean
+ /** The share of the town hall's administration it saves (the town hall's). */
+ readonly admin?: number
+ /** The upgrade after this one. */
+ readonly next?: Upgrade
+}
+
+/** Upgrades a building has had: none, one, or (a town hall) two. */
+export type Level = 0 | 1 | 2
+
+/** The upgrade a building at `level` stands as (`undefined`: none), and the one it could have next. */
+export const upgradeAt = (kind: Pick<Kind, "upgrade">, level: number): Upgrade | undefined =>
+ level <= 0 ? undefined : level === 1 ? kind.upgrade : kind.upgrade?.next
+export const nextUpgrade = (kind: Pick<Kind, "upgrade">, level: number): Upgrade | undefined => upgradeAt(kind, level + 1)
+
+/**
+ * A kind as a building of it stands once upgraded to `level`: its upkeep,
+ * crew, pace, shelves, carriers, walker, and desirability those of its
+ * upgrades. Everything that works a building reads it from here.
+ */
+export const asUpgraded = <K extends Kind>(kind: K, level: number): K => {
+ let k: Kind = kind
+ for (let l = 1; l <= level; l++) {
+ const up = upgradeAt(kind, l)
+ if (!up) break
+ k = {
+ ...k,
+ upkeep: up.upkeep,
+ workers: up.workers ?? k.workers,
+ ...(k.recipe && up.seconds ? { recipe: { ...k.recipe, seconds: up.seconds } } : {}),
+ ...(k.holds && up.cap ? { holds: { ...k.holds, cap: up.cap } } : {}),
+ ...(up.carriers ? { carriers: up.carriers } : {}),
+ ...(k.service && up.service ? { service: { ...k.service, ...up.service } } : {}),
+ ...(up.appeal ? { appeal: up.appeal } : {})
+ }
+ }
+ return k as K
+}
+
+/** Steps of building work an upgrade takes for each good it is made of: a market hall half a minute, a city hall four. */
+export const WORKS_TICKS = ticks(1.5)
+/** The steps of work an upgrade of `total` goods takes. */
+export const worksNeeded = (total: number, rules: { readonly worksTicks: number } = { worksTicks: WORKS_TICKS }) => Math.max(1, total) * rules.worksTicks
+
+/** Coins a minute a building of a kind costs at its level of upgrades. */
+export const upkeepOf = (kind: Pick<Kind, "upkeep" | "upgrade">, level: number): number => upgradeAt(kind, level)?.upkeep ?? kind.upkeep
+
+/** What a building of a kind cost all told, its upgrades included: what pulling it down gives part of back. */
+export const builtCost = (kind: Pick<Kind, "cost" | "upgrade">, level: number): Kind["cost"] => {
+ let coins = kind.cost.coins
+ const materials: Partial<Record<GoodId, number>> = { ...kind.cost.materials }
+ for (let l = 1; l <= level; l++) {
+ const up = upgradeAt(kind, l)
+ if (!up) break
+ coins += up.cost.coins
+ for (const [g, n] of Object.entries(up.cost.materials) as Array<[GoodId, number]>) materials[g] = (materials[g] ?? 0) + n
+ }
+ return { coins, materials }
}
const free = { residents: 0, citizens: 0 }
@@ -189,13 +246,27 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
category: "storage", size: 3, half: 20, stories: 2, roof: "flat", bays: 2, window: 8, topper: "flag",
cost: { coins: 0, materials: {} }, upkeep: 0, workers: 0, crew: "settlers", unlock: free, buildable: false,
holds: { accepts: "all", cap: 100 }, carriers: 6,
- service: { service: "goods", seconds: 8, range: 20 }, appeal: { value: 4, reach: 4, full: 2 }
+ service: { service: "goods", seconds: 8, range: 20 }, appeal: { value: 4, reach: 4, full: 2 },
+ upgrade: {
+ title: "Guildhall", blurb: "the town hall with a clock tower: it holds twice as much, sends more carriers, its walker goes further, and it runs the town for a tenth less", rank: 1,
+ cost: { coins: 500, materials: { planks: 30, stone: 40, tools: 6 } }, upkeep: 8,
+ cap: 200, carriers: 8, service: { seconds: 6, range: 26 }, appeal: { value: 6, reach: 5, full: 2 }, admin: 0.1,
+ next: {
+ title: "City hall", blurb: "a domed seat of the city: it holds the most, sends the most carriers, walks furthest, and runs the city for a fifth less", rank: 2,
+ cost: { coins: 1200, materials: { planks: 50, stone: 80, tools: 15, cloth: 20 } }, upkeep: 16,
+ cap: 300, carriers: 10, service: { seconds: 5, range: 32 }, appeal: { value: 8, reach: 6, full: 3 }, admin: 0.2
+ }
+ }
},
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, crew: "settlers", unlock: free, buildable: true,
- holds: { accepts: "all", cap: 50 }, carriers: 4, appeal: { value: -2, reach: 2 }
+ holds: { accepts: "all", cap: 50 }, carriers: 4, appeal: { value: -2, reach: 2 },
+ upgrade: {
+ title: "Depot", blurb: "a loading yard and a hoist: it holds more than twice as much, and sends two more carriers", rank: 1,
+ cost: { coins: 200, materials: { planks: 10, stone: 10 } }, upkeep: 10, cap: 120, carriers: 6
+ }
},
granary: {
id: "granary", title: "Granary", blurb: "stores food, and keeps fish and bread five times as long",
@@ -221,7 +292,11 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
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, crew: "settlers", unlock: free, buildable: true,
recipe: { input: null, inputs: 0, output: "stone", batch: 1, seconds: 8 }, gathers: { source: "stone", radius: 3 }, carriers: 2,
- wear: 50, dusty: true, appeal: { value: -8, reach: 4 }
+ wear: 50, dusty: true, appeal: { value: -8, reach: 4 },
+ upgrade: {
+ title: "Masonry", blurb: "a derrick and a mason's shed: it goes on cutting worked-out rock at full pace, not a third of it; a dustier neighbour", rank: 2,
+ cost: { coins: 200, materials: { planks: 6, tools: 2 } }, upkeep: 8, deep: true, appeal: { value: -10, reach: 4 }
+ }
},
mine: {
id: "mine", title: "Mine", blurb: "digs ore from a deposit nearby",
@@ -263,7 +338,11 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
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, crew: "settlers", unlock: { residents: 60, 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, appeal: { value: -2, reach: 2 }
+ plants: { what: "field", radius: 2, seconds: 3, max: 8 }, carriers: 2, appeal: { value: -2, reach: 2 },
+ upgrade: {
+ title: "Estate", blurb: "a barn and a dovecote: a third hand reaps the same fields half again as fast", rank: 2,
+ cost: { coins: 250, materials: { planks: 8, stone: 6, tools: 1 } }, upkeep: 7, workers: 3, seconds: 2.5
+ }
},
mill: {
id: "mill", title: "Mill", blurb: "grinds wheat into flour",
@@ -277,7 +356,11 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
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: 1 } }, upkeep: 8, workers: 2, crew: "citizens", unlock: { residents: 60, citizens: 0 }, buildable: true,
recipe: { input: "flour", inputs: 1, output: "bread", batch: 2, seconds: 6 }, holds: { accepts: ["flour", "bread"], cap: 8 }, carriers: 2,
- wear: 60, hot: true, appeal: { value: -4, reach: 3 }
+ wear: 60, hot: true, appeal: { value: -4, reach: 3 },
+ upgrade: {
+ title: "Ovenworks", blurb: "a second oven and a third baker: bread every four seconds instead of six", rank: 2,
+ cost: { coins: 300, materials: { planks: 6, stone: 10, tools: 2 } }, upkeep: 13, workers: 3, seconds: 4
+ }
},
sheep: {
id: "sheep", title: "Sheep farm", blurb: "shears sheep for wool",
@@ -319,7 +402,11 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
id: "firewatch", title: "Fire watch", blurb: "a watchman checks homes and workshops along the way for fire; firefighters run to any blaze",
category: "services", size: 2, half: 9, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
cost: { coins: 70, materials: { planks: 3 } }, upkeep: 3, workers: 2, crew: "settlers", unlock: free, buildable: true,
- service: { service: "fire", seconds: 7, range: 30 }
+ service: { service: "fire", seconds: 7, range: 30 },
+ upgrade: {
+ title: "Fire brigade", blurb: "a bell tower and a pump: its watchman walks further, more often, and four firefighters run instead of two", rank: 2,
+ cost: { coins: 200, materials: { planks: 6, stone: 6, tools: 1 } }, upkeep: 5, service: { seconds: 5, range: 36 }, crews: 4
+ }
},
healer: {
id: "healer", title: "Healer", blurb: "a physician calls on the homes along the way and cures the sick",
diff --git a/src/factory.css b/src/factory.css
index 1772c99..a60e7b3 100644
--- a/src/factory.css
+++ b/src/factory.css
@@ -153,6 +153,10 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
.panel .close:hover { background: #e2e5de; border-color: #c9cec4; }
.panel .sub { margin: 3px 0 0; color: #6c766f; font-size: 12px; line-height: 1.4; }
.panel .sub.warn { color: #b04a39; }
+.panel ul.changes { margin: 6px 0 8px; padding-left: 18px; font-size: 12px; line-height: 1.5; color: #3d4943; }
+.panel ul.changes li::marker { color: #b39a61; }
+.panel .option .gives { display: flex; flex-direction: column; gap: 1px; font-size: 11.5px; line-height: 1.35; color: #3d4943; }
+.panel .option .gives .change::before { content: "· "; color: #b39a61; }
.panel .pill { display: inline-flex; align-items: center; gap: 6px; margin-top: 5px; padding: 2px 9px; border-radius: 999px; font-size: 11px; background: #e2e5de; color: #5d6861; }
.panel .pill::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
.panel .pill.working { background: #e1ecd9; color: #4f8a3e; }
diff --git a/src/host.ts b/src/host.ts
index 40b1ab0..2ccce40 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -62,7 +62,8 @@ import { PICTURE_HEIGHT, PICTURE_QUALITY, PICTURE_WIDTH } from "./share/format.t
import { MapInput } from "./render3d/input.ts"
import { portrait } from "./render3d/portrait.ts"
import { serviceBuilding } from "./asset-lab/service-upgrades.ts"
-import { makeBuilding } from "./asset-lab/buildings.ts"
+import { buildingDimensions, makeBuilding } from "./asset-lab/buildings.ts"
+import { dressedBuilding, isDressed, type DressedKind } from "./asset-lab/upgrade-dress.ts"
import { house } from "./asset-lab/homes.ts"
const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = "") => {
@@ -396,6 +397,7 @@ export const createHost = async (
const ui: UiValue = {
tool: "select",
placing: null,
+ upgrading: null,
ground: "lawn",
prop: "lamp",
menu: null,
@@ -612,7 +614,7 @@ export const createHost = async (
const refreshTools = () => {
for (const { tool, button } of buttons) {
- const on = tool.tool === "build" ? ui.menu === "build" || ui.tool === "place" || ui.tool === "ground" || ui.tool === "prop" : tool.tool === ui.tool
+ const on = tool.tool === "build" ? ui.menu === "build" || ui.tool === "place" || ui.tool === "ground" || ui.tool === "prop" || ui.tool === "upgrade" : tool.tool === ui.tool
button.classList.toggle("on", on)
}
townButton.classList.toggle("on", ui.menu === "town")
@@ -621,6 +623,7 @@ export const createHost = async (
ui.tool = tool
ui.dragFrom = null
if (tool !== "place") ui.placing = null
+ if (tool !== "upgrade") ui.upgrading = null
if (tool !== "select") ui.selected = null
refreshTools()
}
@@ -644,6 +647,14 @@ export const createHost = async (
const title = grounds[ground].title.toLowerCase()
ui.toast(touchScreen() ? `Drag a rectangle to lay ${title}, then tap Build` : `Drag a rectangle to lay ${title} · Esc to stop`)
}
+ /** Picks a kind's buildings to upgrade: each one it can go to is outlined, and the tooltip says what it gives and costs. */
+ const upgradeTool = (kind: KindId) => {
+ ui.menu = null
+ choose("upgrade")
+ ui.upgrading = kind
+ const title = kinds[kind].title.toLowerCase()
+ ui.toast(touchScreen() ? `Tap a ${title} to see its upgrade, then tap it again to begin` : `Click a ${title} to begin its upgrade · Esc to stop`)
+ }
const furnish = (prop: PropId) => {
ui.prop = prop
ui.menu = null
@@ -736,11 +747,12 @@ export const createHost = async (
return url
}
const both = { right: true, left: true }
- const picture = (what: KindId | Tier | `park:${GroundId | PropId}`, upgraded = false): HTMLImageElement => {
+ const picture = (what: KindId | Tier | `park:${GroundId | PropId}`, level: number | boolean = 0): HTMLImageElement => {
const img = document.createElement("img")
img.className = "thumb"
img.alt = ""
- const id = `${String(what)}${upgraded ? "/upgraded" : ""}`
+ const lvl = Number(level), upgraded = lvl > 0
+ const id = `${String(what)}${upgraded ? `/upgraded${lvl}` : ""}`
let url = pictures.get(id)
if (!url) {
if (typeof what === "string" && what.startsWith("park:")) {
@@ -750,6 +762,8 @@ export const createHost = async (
void url.finally(() => g.destroy())
} else if (what === 1 || what === 2 || what === 3) url = modelPicture(() => house(what, undefined, undefined, { doors: { right: true } }))
else if (upgraded && (what === "market" || what === "chapel")) url = modelPicture(() => serviceBuilding(what, 2, { doors: both }))
+ else if (upgraded && isDressed(what as KindId))
+ url = modelPicture(() => dressedBuilding(what as DressedKind, lvl, makeBuilding(what as KindId, { doors: both, motion: false }), buildingDimensions(what as KindId).height))
else url = modelPicture(() => makeBuilding(what as KindId, { doors: both, motion: false }))
pictures.set(id, url)
}
@@ -912,6 +926,41 @@ export const createHost = async (
}
panel.append(box)
}
+ // Upgrades: every building that can be upgraded where it stands, what it becomes, what it gives, and what it costs.
+ const upgrades = section(
+ "upgrades",
+ "build",
+ "An upgrade is made where the building stands, so it needs no more land. Its coins are paid when the works begin; carriers then bring its materials, scaffolding rises around it, and it goes on working meanwhile. Pick one, then click the building."
+ )
+ upgrades.style.borderTop = "3px solid #b39a61"
+ // The town hall's first: it grows with the town; then the rest in the build menu's order.
+ for (const u of [...(ui.stats?.upgrades ?? [])].sort((a, b) => Number(b.kind === "townhall") - Number(a.kind === "townhall"))) {
+ const option = el("button", "option")
+ const cost = costChips({ coins: u.coins, materials: u.materials })
+ cost.box.prepend(el("span", "cap", "cost"))
+ const terms = el("span", "gives")
+ terms.innerHTML = `<span class="cap">gives</span>${u.changes.map((c) => `<span class="change">${c}</span>`).join("")}`
+ const blurb = el("span", "blurb", u.blurb)
+ option.append(picture(u.kind, u.level + 1), el("span", "name", `${u.from} → ${u.to}`), cost.box, terms, blurb)
+ option.title = `${u.from} → ${u.to}: ${u.blurb} · ${u.price} · ${u.changes.join(" · ")}`
+ option.onclick = () => upgradeTool(u.kind)
+ live.push(() => {
+ const now = ui.stats?.upgrades.find((x) => x.kind === u.kind && x.level === u.level)
+ option.style.display = now ? "" : "none"
+ if (!now) return
+ const short = cost.refresh()
+ option.disabled = now.blocked !== null || now.ready === 0
+ option.classList.toggle("short", now.blocked === null && short)
+ option.classList.toggle("on", ui.tool === "upgrade" && ui.upgrading === u.kind)
+ blurb.textContent = now.blocked
+ ? now.blocked
+ : now.ready === 0
+ ? now.underway > 0 ? `under way: ${now.underway}` : `build a ${kinds[u.kind].title.toLowerCase()} first`
+ : `${now.ready} ready${now.underway > 0 ? ` · ${now.underway} under way` : ""} · ${u.blurb}`
+ })
+ upgrades.append(option)
+ }
+ panel.append(upgrades)
// Parks are laid out piece by piece: ground first, then what stands on it.
const parks = section(
"parks",
@@ -1304,14 +1353,13 @@ export const createHost = async (
if (p.type === "build") return buildMenu()
if (p.type === "town") return townPanel()
- const upgrade = p.type === "building" && p.upgraded ? kinds[p.kind].upgrade : undefined
- const title = p.type === "building" ? (upgrade ?? kinds[p.kind]).title.toLowerCase() : p.type === "house" ? tierHome[p.tier] : p.type === "park" ? "park" : "ruin"
+ const title = p.type === "building" ? p.title.toLowerCase() : p.type === "house" ? tierHome[p.tier] : p.type === "park" ? "park" : "ruin"
const status = el("span", "pill")
const about = el(
"p",
"sub",
p.type === "building"
- ? (upgrade ?? kinds[p.kind]).blurb
+ ? p.blurb
: p.type === "ruin"
? "bulldoze it to clear the plot"
: p.type === "park"
@@ -1324,7 +1372,7 @@ export const createHost = async (
)
const below = el("div", "")
below.append(status, about)
- panel.append(header(title, p.type === "ruin" ? iconEl("condition", 30) : p.type === "park" ? iconEl("decor", 30) : picture(p.type === "building" ? p.kind : p.tier, p.type === "building" && p.upgraded), below))
+ panel.append(header(title, p.type === "ruin" ? iconEl("condition", 30) : p.type === "park" ? iconEl("decor", 30) : picture(p.type === "building" ? p.kind : p.tier, p.type === "building" ? p.level : 0), below))
// A building or a home: its rows in boxes under headings, kept in step with what the town says each frame.
// A park or a ruin: one box.
const holder = el("div", "")
@@ -1369,7 +1417,30 @@ export const createHost = async (
syncGroups([{ title: "what is left", icon: "condition", lines: now.lines }])
}
})
- if (!(p.type === "building" && p.kind === "townhall")) {
+ // What upgrading it would give and cost, said in full before the mayor pays for it.
+ if (p.type === "building" && p.upgrade) {
+ const box = section(`upgrade to ${p.upgrade.title.toLowerCase()}`, "build", p.upgrade.blurb)
+ box.classList.add("lines")
+ const price = el("p", "sub", p.upgrade.price)
+ const list = el("ul", "changes")
+ for (const c of p.upgrade.changes) list.append(el("li", "", c))
+ const begin = el("button", "frame primary", `Begin the ${p.upgrade.title.toLowerCase()}`)
+ begin.onclick = () => {
+ const now = ui.panel
+ if (now?.type === "building") ui.edits.push({ type: "upgrade", cell: now.cell })
+ }
+ const why = el("p", "sub", "")
+ live.push(() => {
+ const now = ui.panel
+ if (now?.type !== "building" || !now.upgrade) return
+ begin.disabled = now.upgrade.blocked !== null || now.upgrade.short !== null
+ why.textContent = now.upgrade.blocked ?? now.upgrade.short ?? "the coins are paid now; carriers bring the rest, and it goes on working"
+ })
+ box.append(price, list, begin, why)
+ panel.append(box)
+ }
+ if (p.type === "building" && p.kind === "townhall") return
+ {
const actions = el("div", "actions")
if (p.type === "building") {
const pause = el("button", "frame", "Pause work")
@@ -1385,21 +1456,6 @@ export const createHost = async (
pause.style.display = now.pausable ? "" : "none"
})
actions.append(pause)
- // A building that can be upgraded where it stands (see `Kind.upgrade`).
- if (p.upgrade) {
- const up = el("button", "frame primary", `Upgrade: ${p.upgrade.title.toLowerCase()}`)
- up.onclick = () => {
- const now = ui.panel
- if (now?.type === "building") ui.edits.push({ type: "upgrade", cell: now.cell })
- }
- live.push(() => {
- const now = ui.panel
- if (now?.type !== "building" || !now.upgrade) return
- up.disabled = now.upgrade.blocked !== null
- up.title = `${kinds[now.kind].upgrade?.blurb ?? ""} · ${now.upgrade.cost}${now.upgrade.blocked ? ` · ${now.upgrade.blocked}` : ""}`
- })
- actions.append(up)
- }
}
if (p.type === "house") {
const close = el("button", "frame", "Close home")
@@ -1435,7 +1491,7 @@ export const createHost = async (
? ""
: p.type === "build" || p.type === "town"
? p.type
- : `${p.type}|${p.id}|${p.type === "house" ? p.tier : p.type === "building" ? `${p.upgraded}|${p.upgrade !== null}` : ""}`
+ : `${p.type}|${p.id}|${p.type === "house" ? p.tier : p.type === "building" ? `${p.level}|${p.upgrade?.title ?? ""}|${p.works !== null}` : ""}`
if (next !== shape) {
shape = next
// Keep the old contents while the closed panel slides away.
diff --git a/src/present.ts b/src/present.ts
index cdc1a03..7e9a4d6 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -13,7 +13,7 @@ import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, Rui
import type { DoorSet, OverlayCell } from "./render3d/models.ts"
import {
amounts, BUILD_TICKS, builtCost, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,
- PAVE_COST, propIds, props, ranks, risk, RISK_MAX, ROAD_COST, tierHome, total, upkeepOf, winters, type Amounts, type GoodId, type Kind, type KindId, type Need, type Tier
+ kindOrder, nextUpgrade, worksNeeded, PAVE_COST, propIds, props, ranks, risk, RISK_MAX, ROAD_COST, tierHome, total, upgradeAt, upkeepOf, winters, type Amounts, type GoodId, type Kind, type KindId, type Need, type Tier
} from "./content.ts"
import { around, canPlace, cellOf, doors, entrances, isRoad, key, lPath, nearest, reach, useAt, type TileLike } from "./grid.ts"
import { GRID, inside, U, type Point } from "./iso.ts"
@@ -48,6 +48,7 @@ import {
Park,
Paused,
Upgraded,
+ Works,
Paved,
Policy,
Recipe,
@@ -87,6 +88,7 @@ import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, season
import { Townsfolk } from "./townsfolk.ts"
import { emptyPreview, type Alert as Notice, type Group, type HitBox, type Legend, type Line, type View } from "./ui.ts"
import { blockers as blockersOf, streetAdvice, streetShort, whyUnmet, type InTown, type Served, type Street } from "./rules/explain.ts"
+import { upgradeChanges, upgradePrice } from "./rules/upgrades.ts"
import { breadBonus, moreAdmin, shortOf, streetTax, suppliedTaxOf, taxOutlook, type TaxedHome } from "./rules/households.ts"
import { approvalTarget } from "./rules/approval.ts"
import { salvageOf, salvageText } from "./rules/salvage.ts"
@@ -189,6 +191,7 @@ const BuildingRead = Game.Query({
hall: Game.Query.optional(TownHall),
paused: Game.Query.optional(Paused),
upgraded: Game.Query.optional(Upgraded),
+ works: Game.Query.optional(Works),
risk: Game.Query.optional(Risk),
condition: Game.Query.optional(Condition),
burning: Game.Query.optional(Burning)
@@ -224,6 +227,9 @@ const buildOf = (
rising: { readonly ticks: number } | undefined
) => (site ? PLATE_SHARE + (SITE_SHARE - PLATE_SHARE) * delivered(site) : rising ? rising.ticks / BUILD_TICKS : 1)
+/** An upgrade under way: the share of its work done (see `Works`), else `null`. */
+const worksShare = (works: { readonly total: number; readonly done: number } | undefined) =>
+ works ? Math.min(1, works.done / worksNeeded(works.total)) : null
const siteShare = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined) =>
site ? delivered(site) : null
@@ -520,6 +526,24 @@ export const Interact = Game.System(
ui.edits.push({ type: "building", kind: ui.placing, cell: at, open: false })
break
}
+ case "upgrade": {
+ // A click on a building of the kind being upgraded begins its works.
+ if (gesture.panned) break
+ const hit = pickAt(gesture.at, gesture.hit)
+ const row = hit !== null ? buildings.find((b) => b.entity.id === hit) : undefined
+ const kind = row ? kinds[row.data.building.get().kind] : undefined
+ if (!row || !kind || (ui.upgrading && kind.id !== ui.upgrading)) {
+ const wanted = ui.upgrading ? (upgradeAt(kinds[ui.upgrading], 0) ? kinds[ui.upgrading].title.toLowerCase() : "building") : "building"
+ ui.toast(`Pick a ${wanted} to upgrade`)
+ break
+ }
+ if (row.data.works.present) {
+ ui.toast(`The ${kind.title.toLowerCase()} is already being upgraded`)
+ break
+ }
+ ui.edits.push({ type: "upgrade", cell: row.data.tile.get() })
+ break
+ }
case "bulldoze": {
if (gesture.panned) break
const hit = pickAt(gesture.at, gesture.hit)
@@ -540,7 +564,7 @@ export const Interact = Game.System(
const preview = emptyPreview()
const pointer = ui.pointer
const cell = pointer ? cellAt(pointer) : null
- preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze") ? pickAt(pointer, ui.pointerHit) : null
+ preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze" || ui.tool === "upgrade") ? pickAt(pointer, ui.pointerHit) : 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" })
@@ -648,6 +672,26 @@ export const Interact = Game.System(
// No road at a side's middle: shown red under the ghost, as it will not be laid there.
if (placeProblem(kind, tile)?.refuse) preview.plots.push({ ...tile, look: "blocked" })
} else preview.plots.push({ ...tile, look: "blocked" })
+ } else if (ui.tool === "upgrade" && ui.upgrading) {
+ // Every building the upgrade can go to, outlined; the one under the pointer says what it would give and cost.
+ const rank = resources.fate.get().rank, coins = resources.treasury.get().coins
+ for (const row of buildings) {
+ const { data } = row
+ if (data.building.get().kind !== ui.upgrading || data.site.present || data.rising.present) continue
+ const kind = kinds[ui.upgrading], level = maybe(data.upgraded)?.level ?? 0, up = nextUpgrade(kind, level)
+ const tile = data.tile.get()
+ if (!up) continue
+ const blocked = upgradeBlock(up, rank, { ranks })
+ const hovered = preview.hover === row.entity.id
+ preview.plots.push({ ...tile, look: data.works.present || blocked ? "blocked" : hovered ? "picked" : "reach" })
+ if (!hovered) continue
+ const from = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()
+ preview.tooltip = data.works.present
+ ? `${from} → ${up.title.toLowerCase()} · under way: carriers are bringing its materials`
+ : [`${from} → ${up.title.toLowerCase()}`, upgradePrice(up), ...upgradeChanges(kind, level).map((c) => `· ${c}`),
+ blocked ?? (coins < up.cost.coins ? `${up.cost.coins - coins} coins short` : "click to begin: it goes on working meanwhile")].join("\n")
+ }
+ if (!preview.tooltip) preview.tooltip = `upgrade: pick a ${kinds[ui.upgrading].title.toLowerCase()} · Esc to stop`
} else if (ui.tool === "bulldoze") {
preview.danger = true
if ((preview.hover === null || useAt(grid, cell?.x ?? -1, cell?.y ?? -1) === "park") && cell && ["road", "tree", "field", "park"].includes(useAt(grid, cell.x, cell.y)))
@@ -683,7 +727,7 @@ export const Interact = Game.System(
sources = []
for (const { data } of buildings) {
if (data.site.present || data.rising.present) continue
- const s = buildingSource(data.building.get().kind, data.tile.get(), undefined, data.upgraded.present)
+ const s = buildingSource(data.building.get().kind, data.tile.get(), undefined, maybe(data.upgraded)?.level ?? 0)
if (s) sources.push(s)
}
for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get()))
@@ -775,8 +819,8 @@ export const Interact = Game.System(
: { icon: "tools", label: "tools", value: "none", tone: "bad", note: "half pace until one comes: a smithy makes them, or buy them in the town panel" }
)
const running: Array<Line> = []
- const upgraded = row.data.upgraded.present
- const upkeep = upkeepOf(kind, upgraded)
+ const level = maybe(row.data.upgraded)?.level ?? 0
+ const upkeep = upkeepOf(kind, level)
if (upkeep > 0) running.push({ icon: "upkeep", label: "upkeep", value: `${upkeep} coins a minute` })
const condition = maybe(row.data.condition)
if (condition)
@@ -796,7 +840,7 @@ export const Interact = Game.System(
tone: r.fire >= risk.warn ? "bad" : r.fire >= RISK_MAX * 0.35 ? "warn" : "ok",
note: r.fire >= RISK_MAX * 0.35 ? "a fire watch's watchman lowers it as he passes" : undefined
})
- const appealHere = (upgraded ? kind.upgrade?.appeal : undefined) ?? kind.appeal
+ const appealHere = upgradeAt(kind, level)?.appeal ?? kind.appeal
if (appealHere) running.push({ icon: "appeal", label: "desirability nearby", value: signed(appealHere.value) })
const help = [
upkeep > 0 ? "Upkeep is paid every minute it stands, a quarter of it while paused." : "",
@@ -992,11 +1036,15 @@ export const Interact = Game.System(
const hoveredBuilding = hovered !== null ? buildings.find((row) => row.entity.id === hovered) : undefined
const hoveredHouse = hovered !== null ? houses.find((row) => row.entity.id === hovered) : undefined
const hoveredRuin = hovered !== null ? ruins.find((row) => row.entity.id === hovered) : undefined
- if (hoveredBuilding) {
+ // The upgrade tool says what an upgrade gives and costs instead (see above).
+ if (ui.tool === "upgrade") {
+ } else if (hoveredBuilding) {
const { kind, status, problem } = describeBuilding(hoveredBuilding)
+ const level = maybe(hoveredBuilding.data.upgraded)?.level ?? 0, works = maybe(hoveredBuilding.data.works)
+ const title = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()
preview.tooltip = ui.tool === "bulldoze"
- ? `${kind.title.toLowerCase()} · ${hoveredBuilding.data.hall.present ? "the town hall stays" : salvageFor(builtCost(kind, hoveredBuilding.data.upgraded.present), maybe(hoveredBuilding.data.site))}`
- : `${kind.title.toLowerCase()} · ${problem ?? status}`
+ ? `${title} · ${hoveredBuilding.data.hall.present ? "the town hall stays" : salvageFor(builtCost(kind, level), maybe(hoveredBuilding.data.site))}`
+ : `${title} · ${problem ?? status}${works ? ` · becoming a ${upgradeAt(kind, works.level)!.title.toLowerCase()}, ${Math.round(worksShare(works)! * 100)}% built` : ""}`
} else if (hoveredHouse) {
const h = hoveredHouse.data.house.get()
const t = hoveredHouse.data.tile.get()
@@ -1034,29 +1082,43 @@ export const Interact = Game.System(
const { kind, status, problem, groups } = describeBuilding(pickedBuilding)
const standing = !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present
const pausable = kind.id !== "townhall" && standing
- const upgraded = pickedBuilding.data.upgraded.present
- const up = kind.upgrade
- const upgradeOffer = up && standing && !upgraded ? { title: up.title, cost: costText(up.cost), blocked: upgradeBlock(up, resources.fate.get().rank, { ranks }) } : null
- // The upgrade it could have, as a box of its own: what it is, what it costs, and what keeps it from it now.
- if (up && upgradeOffer)
- groups.push({
- title: `upgrade to ${up.title.toLowerCase()}`,
+ const level = maybe(pickedBuilding.data.upgraded)?.level ?? 0
+ const now = upgradeAt(kind, level)
+ const works = maybe(pickedBuilding.data.works)
+ const up = works ? undefined : nextUpgrade(kind, level)
+ const upgradeOffer = up && standing
+ ? { title: up.title, blurb: up.blurb, price: upgradePrice(up), changes: upgradeChanges(kind, level),
+ blocked: upgradeBlock(up, resources.fate.get().rank, { ranks }),
+ short: resources.treasury.get().coins < up.cost.coins ? `${up.cost.coins - resources.treasury.get().coins} coins short` : null }
+ : null
+ // An upgrade under way: what it is to become, and what carriers still have to bring.
+ const worksOf = works
+ ? { title: upgradeAt(kind, works.level)!.title, share: worksShare(works)!,
+ left: costText({ coins: 0, materials: Object.fromEntries(goodIds.filter((g) => works.owed[g] > 0).map((g) => [g, works.owed[g]])) }) }
+ : null
+ if (worksOf)
+ groups.unshift({
+ title: `becoming a ${worksOf.title.toLowerCase()}`,
icon: "build",
- lines: [{ icon: "coins", label: "costs", value: upgradeOffer.cost, tone: upgradeOffer.blocked ? "dim" : undefined, note: upgradeOffer.blocked ?? up.blurb }]
+ lines: [{ icon: "build", label: "built", value: `${Math.round(worksOf.share * 100)}%`, tone: "warn", note: worksOf.left ? `carriers still bring ${worksOf.left}; it works on meanwhile` : "everything is in: the builders are finishing; it works on meanwhile" }]
})
ui.panel = {
type: "building",
id: pickedBuilding.entity.id,
cell: pickedBuilding.data.tile.get(),
kind: kind.id,
+ title: now?.title ?? kind.title,
+ blurb: now?.blurb ?? kind.blurb,
status,
problem,
groups,
pausable,
paused: pickedBuilding.data.paused.present,
- salvage: salvageFor(builtCost(kind, upgraded), maybe(pickedBuilding.data.site)),
- upgraded,
- upgrade: upgradeOffer
+ salvage: salvageFor(builtCost(kind, level), maybe(pickedBuilding.data.site)),
+ level,
+ upgraded: level > 0,
+ upgrade: upgradeOffer,
+ works: worksOf
}
} else if (pickedHouse) {
const { h, summary, trouble, groups } = describeHouse(pickedHouse)
@@ -1245,6 +1307,40 @@ export const Interact = Game.System(
if (empty && tick - emptySince! >= HUNGER_PATIENCE) hungryUntil = tick + HUNGER_PATIENCE
if (hungryUntil > tick + HUNGER_PATIENCE) hungryUntil = 0
if (census.homes > 0 && tick < hungryUntil) alerts.push({ tone: "bad", text: "no food in store, so homes go hungry and pay no taxes: build another fishery, or buy fish in the [town] panel", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })
+ // ── Upgrades: what the town could upgrade, kind by kind and level by level ──
+ const rank = resources.fate.get().rank
+ const upgradeRows = new Map<string, { kind: KindId; level: number; ready: number; underway: number; first: (typeof buildings)[number] | null }>()
+ // Every buildable kind's first upgrade is listed, built or not, so the menu says what is to come; the town hall's by where it stands.
+ for (const id of kindOrder) if (kinds[id].upgrade) upgradeRows.set(`${id}:0`, { kind: id, level: 0, ready: 0, underway: 0, first: null })
+ for (const row of buildings) {
+ const { data } = row
+ if (data.site.present || data.rising.present) continue
+ const kind = kinds[data.building.get().kind]
+ const level = maybe(data.upgraded)?.level ?? 0
+ const works = maybe(data.works)
+ const from = works ? works.level - 1 : level
+ if (!nextUpgrade(kind, from)) continue
+ const k = `${kind.id}:${from}`
+ const entry = upgradeRows.get(k) ?? { kind: kind.id, level: from, ready: 0, underway: 0, first: null }
+ if (works) entry.underway += 1
+ else {
+ entry.ready += 1
+ entry.first ??= row
+ }
+ upgradeRows.set(k, entry)
+ }
+ const upgrades = [...upgradeRows.values()].map((r) => {
+ const kind = kinds[r.kind], up = nextUpgrade(kind, r.level)!
+ return {
+ kind: r.kind, level: r.level, from: (upgradeAt(kind, r.level)?.title ?? kind.title).toLowerCase(), to: up.title.toLowerCase(), blurb: up.blurb,
+ coins: up.cost.coins, materials: up.cost.materials, price: upgradePrice(up), changes: upgradeChanges(kind, r.level),
+ blocked: upgradeBlock(up, rank, { ranks }), ready: r.ready, underway: r.underway, first: r.first
+ }
+ })
+ // A word when an upgrade is open and nothing is being upgraded: where they are found.
+ const open = upgrades.find((u) => u.blocked === null && u.ready > 0 && u.first)
+ if (open && !upgrades.some((u) => u.underway > 0) && resources.treasury.get().coins >= open.coins)
+ alerts.push({ tone: "hint", text: `the ${open.from} can become a ${open.to}: [build] → upgrades says what it gives and costs`, at: open.first!.data.tile.get(), size: open.first!.data.tile.get().size, id: open.first!.entity.id })
const ledger = resources.ledger.get()
const charter = resources.charter.get()
const t = elapsed(resources.time.get(), charter)
@@ -1485,6 +1581,7 @@ export const Interact = Game.System(
history: resources.history.get().samples,
chronicle: resources.chronicle.get().lines,
alerts,
+ upgrades: upgrades.map(({ first: _first, ...u }) => u),
guide: {
step:
step && shown
@@ -1717,7 +1814,8 @@ export const Animate = Game.System(
beat: recipe ? recipe.made : maybe(data.service) ? walkers : 0,
doors: doorsOf(grid, data.tile.get()),
site: siteShare(maybe(data.site)),
- upgraded: data.upgraded.present
+ level: maybe(data.upgraded)?.level ?? 0,
+ works: worksShare(maybe(data.works))
},
dt,
emphasis(entity.id)
diff --git a/src/render3d/models.ts b/src/render3d/models.ts
index c16232e..9737831 100644
--- a/src/render3d/models.ts
+++ b/src/render3d/models.ts
@@ -12,6 +12,8 @@ import { setts } from "../asset-lab/town-props.ts"
import { isWorkshop, workshopConstruction } from "../asset-lab/workshops.ts"
import { isTradeYard, tradeConstruction } from "../asset-lab/trades.ts"
import { serviceBuilding, upgradeHeights, type ServiceKind } from "../asset-lab/service-upgrades.ts"
+import { dressedBuilding, dressedTop, isDressed, scaffoldAsset } from "../asset-lab/upgrade-dress.ts"
+export { scaffoldAsset }
export type DoorSet = Record<Side, boolean>
export const noDoors: DoorSet = { right: false, left: false, backRight: false, backLeft: false }
@@ -65,12 +67,16 @@ export function constructionAsset(size: number, half: number, height: number, bu
if (stage.walls > 0) d.box(0, 0, a, a, 0, Math.max(2, Math.round(height * stage.walls)))
return d.asset
}
-/** The height a building of a kind is drawn to its eaves, upgraded or not (see `upgradeHeights`). */
-export const buildingHeight = (id: KindId, upgraded = false) =>
- upgraded && isUpgradable(id) ? upgradeHeights[id].eave : buildingDimensions(id).height
+/** The height a building of a kind is drawn to its eaves at its level of upgrades (see `upgradeHeights`). */
+export const buildingHeight = (id: KindId, level = 0) =>
+ level > 0 && isUpgradable(id) ? upgradeHeights[id].eave : buildingDimensions(id).height
+/** Its highest point, for the marker over it. */
+export const buildingTop = (id: KindId, level = 0) =>
+ level > 0 && isUpgradable(id) ? upgradeHeights[id].top : level > 0 && isDressed(id) ? Math.max(buildingDimensions(id).top, dressedTop(id, level, buildingDimensions(id).height)) : buildingDimensions(id).top
const isUpgradable = (id: KindId): id is ServiceKind => id === "market" || id === "chapel"
-export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number, appearance: Appearance = {}, upgraded = false) {
+export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number, appearance: Appearance = {}, level = 0) {
+ const upgraded = level > 0
const kind = kinds[id],
stage = buildStages(build)
if (build < 0.78) return isWorkshop(id)
@@ -78,9 +84,11 @@ export function buildingAsset(id: KindId, build: number, share: number | null, d
: isTradeYard(id) ? tradeConstruction(id, build, share, doors)
: constructionAsset(kind.size, kind.half, kind.roof === "gable" ? 20 : kind.stories * 32, build, share)
// An upgraded building is only ever a standing one: the upgrade is paid and done at once.
- if (upgraded && isUpgradable(id)) return withAppearance(serviceBuilding(id, 2, { plate: false, doors }), kind.half * U, buildingHeight(id, true), appearance)
- const asset = makeBuilding(id, { doors, open, fit: stage.fit, plate: false, motion: false } satisfies BuildingOptions)
+ if (upgraded && isUpgradable(id)) return withAppearance(serviceBuilding(id, 2, { plate: false, doors }), kind.half * U, buildingHeight(id, level), appearance)
const dimensions = buildingDimensions(id)
+ const own = makeBuilding(id, { doors, open, fit: stage.fit, plate: false, motion: false } satisfies BuildingOptions)
+ // Any other upgrade is the building's own model with what the upgrade adds drawn on (see `upgrade-dress.ts`).
+ const asset = upgraded && isDressed(id) && build >= 1 ? dressedBuilding(id, level, own, dimensions.height) : own
return build >= 1 ? withAppearance(asset, dimensions.half, dimensions.height, appearance) : asset
}
export function homeAsset(tier: Tier, n: number, build: number, share: number | null, doors: DoorSet, appearance: Appearance = {}) {
diff --git a/src/render3d/views.ts b/src/render3d/views.ts
index 1f5d810..c7fe8b8 100644
--- a/src/render3d/views.ts
+++ b/src/render3d/views.ts
@@ -19,13 +19,12 @@ import { makeSails, makeFlag, buildingSmokeOrigin, buildingDimensions } from "..
import { makeMarker } from "../asset-lab/construction.ts"
import { makeRuin } from "../asset-lab/town-props.ts"
import { StructureEffects } from "./structure-effects.ts"
-import { upgradeHeights } from "../asset-lab/service-upgrades.ts"
import { SmokePlume } from "./smoke-effects.ts"
import { surfaceState, type SurfaceState } from "./surface-state.ts"
import { makePerson, serviceCostume, type ServiceRole } from "../asset-lab/people.ts"
import { makeTree, makeRock, makeField, hash } from "../asset-lab/land.ts"
import { ModelHandle } from "./pool.ts"
-import { buildingAsset, buildingHeight, homeAsset, homeKey, doorKey, noDoors, quantizeBuild, plateAsset, treeVariant } from "./models.ts"
+import { buildingAsset, buildingHeight, buildingTop, homeAsset, homeKey, doorKey, noDoors, quantizeBuild, plateAsset, scaffoldAsset, treeVariant } from "./models.ts"
import type { GameScene, SceneNode } from "./scene.ts"
/** Winter's cold light complements the roof snow shader. */
@@ -91,6 +90,7 @@ export class BuildingView extends WorldView {
private plate: ModelHandle
private marker: ModelHandle
private motion: ModelHandle
+ private scaffold: ModelHandle
private smoke: SmokePlume | null = null
private effectLayout = ""
private wave = 0
@@ -104,6 +104,7 @@ export class BuildingView extends WorldView {
this.plate = this.model()
this.marker = this.model()
this.motion = this.model()
+ this.scaffold = this.model()
this.marker.use("problem-marker", makeMarker)
this.marker.root.visible = false
this.body.root.add(this.motion.root)
@@ -125,30 +126,37 @@ export class BuildingView extends WorldView {
this.pulse = Math.max(0, this.pulse - dt * 3)
this.opening += (Number(look.working || this.pulse > 0.2) - this.opening) * Math.min(1, dt * 6)
const open = Math.round(this.opening * 4) / 4
- // An upgraded building (a market hall, a church) is its own model, turned to face the road.
- const upgraded = !!look.upgraded && build >= 1
- this.body.use(`building/${this.kindId}/${upgraded ? 2 : 1}/${build}/${share}/${doorKey(doors)}/${upgraded ? 0 : open}`, () =>
- buildingAsset(this.kindId, build, share, doors, open, {}, upgraded)
+ // An upgraded building is drawn as its upgrade: a market hall or a church its own model, turned to face the
+ // road; anything else its own model with what the upgrade adds (see `upgrade-dress.ts`).
+ const level = build >= 1 ? look.level ?? 0 : 0, upgraded = level > 0
+ this.body.use(`building/${this.kindId}/${level + 1}/${build}/${share}/${doorKey(doors)}/${upgraded ? 0 : open}`, () =>
+ buildingAsset(this.kindId, build, share, doors, open, {}, level)
)
+ // While an upgrade is under way, scaffolding stands inside its plot, rising with what has been brought.
+ const works = look.works ?? null
+ this.scaffold.root.visible = works !== null && build >= 1
+ if (works !== null && build >= 1) {
+ const step = Math.round(works * 6) / 6, height = buildingHeight(this.kindId, level)
+ this.scaffold.use(`scaffold/${kind.size}/${height}/${step}`, () => scaffoldAsset(kind.size, height, step))
+ }
this.plate.use(`plate/${kind.size}/${build}`, () => plateAsset(kind.size, build))
this.body.root.scale.set(1 + this.pulse * 0.04, 1 - this.pulse * 0.06, 1 + this.pulse * 0.04)
- const dimensions = buildingDimensions(this.kindId), H = buildingHeight(this.kindId, upgraded)
- const top = upgraded
- ? upgradeHeights[this.kindId as "market" | "chapel"].top
- : dimensions.top
+ const dimensions = buildingDimensions(this.kindId), H = buildingHeight(this.kindId, level)
+ const top = buildingTop(this.kindId, level)
this.marker.root.position.set(0, (top + 8) / Math.cos(Math.PI / 6), 0)
const signed = !!look.burning || (look.alert !== null && look.alert !== undefined)
this.marker.root.visible = look.problem && look.build >= 1 && !signed
const state = structureState(look,this.stage.frost)
this.body.effects = build >= 1 ? state : surfaceState()
- this.body.effectBounds.set((upgraded ? kind.half * U : dimensions.half) * 32 * Math.SQRT2,H/Math.cos(Math.PI/6),this.entity%97/97,1)
- const effectLayout = `${upgraded ? 2 : 1}/${doorKey(doors)}`
+ const serviceModel = upgraded && (this.kindId === "market" || this.kindId === "chapel")
+ this.body.effectBounds.set((serviceModel ? kind.half * U : dimensions.half) * 32 * Math.SQRT2,H/Math.cos(Math.PI/6),this.entity%97/97,1)
+ const effectLayout = `${level + 1}/${doorKey(doors)}`
if (this.effects && this.effectLayout !== effectLayout) {
this.effects.dispose()
this.effects = null
}
if(!this.effects&&build>=1&&(state.burning||state.fireRisk)){
- this.effects = new StructureEffects(buildingAsset(this.kindId,1,null,doors,0,{},upgraded),H)
+ this.effects = new StructureEffects(buildingAsset(this.kindId,1,null,doors,0,{},level),H)
this.effectLayout = effectLayout
this.effects.group.userData.upgraded=upgraded
this.group.add(this.effects.group)
@@ -156,7 +164,7 @@ export class BuildingView extends WorldView {
this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)
this.shade = 0xffffff
// The market hall has no flag of its own: the flag stays on the tier 1 market.
- this.motion.root.visible = look.build >= 1 && !upgraded && (kind.topper === "flag" || kind.topper === "sails")
+ this.motion.root.visible = look.build >= 1 && !serviceModel && (kind.topper === "flag" || kind.topper === "sails")
if (kind.topper === "flag") {
this.wave += dt * (look.working ? 6 : 3)
this.motion.use("flag/" + this.kindId, () => makeFlag(this.kindId))
diff --git a/src/rules/config.ts b/src/rules/config.ts
index 5536e6b..3457732 100644
--- a/src/rules/config.ts
+++ b/src/rules/config.ts
@@ -16,7 +16,7 @@ const inputs = () => ({
commute: content.COMMUTE, apprentice: content.APPRENTICE, toolStock: content.TOOL_STOCK,
conditionMax: content.CONDITION_MAX, riskMax: content.RISK_MAX, pausedUpkeep: content.PAUSED_UPKEEP, salvage: content.salvage,
buildTicks: content.BUILD_TICKS, roadCost: content.ROAD_COST, paveCost: content.PAVE_COST, pavedPace: content.PAVED_PACE,
- grown: content.GROWN, faceTicks: content.FACE_TICKS, restockTicks: content.RESTOCK_TICKS, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,
+ grown: content.GROWN, faceTicks: content.FACE_TICKS, restockTicks: content.RESTOCK_TICKS, worksTicks: content.WORKS_TICKS, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,
spreadTicks: content.ticks(1.5), growTicks: 10
})
diff --git a/src/rules/guide.ts b/src/rules/guide.ts
index 94a88fb..b742ff7 100644
--- a/src/rules/guide.ts
+++ b/src/rules/guide.ts
@@ -447,7 +447,7 @@ export const guideSteps: ReadonlyArray<GuideStep> = [
{
id: "markethall",
chapter: "Keeping it standing",
- action: "Select a market and upgrade it to a market hall, from its panel.",
+ action: "Open [build], pick the market hall under upgrades, and {tap|click} a market.",
why: "Some homes are beyond every food walker. A market hall's walker goes further and more often, without a second market's upkeep.",
goal: "a market hall stands",
focus: { kind: "market" },
diff --git a/src/rules/households.ts b/src/rules/households.ts
index 10b7193..ae7e235 100644
--- a/src/rules/households.ts
+++ b/src/rules/households.ts
@@ -76,8 +76,8 @@ export const tierFor = (h: Needs, desirability: number, r: { readonly fire: numb
return fits(3) && kept(r, rules) ? 3 : 2
}
-/** Coins a minute the town hall's administration costs for `residents` people in its homes. */
-export const adminOf = (residents: number, rules: Rules = shippedRules): number => Math.round(residents * (rules.admin.perResident + residents / rules.admin.growth))
+/** Coins a minute the town hall's administration costs for `residents` people in its homes, less the share a finer hall `saves`. */
+export const adminOf = (residents: number, rules: Rules = shippedRules, saves = 0): number => Math.round(residents * (rules.admin.perResident + residents / rules.admin.growth) * (1 - saves))
/** What `more` residents add to the administration of a town of `residents`, coins a minute (not rounded). */
export const moreAdmin = (residents: number, more = 1, rules: Rules = shippedRules): number => {
const cost = (n: number) => n * (rules.admin.perResident + n / rules.admin.growth)
@@ -195,8 +195,8 @@ export const taxOutlook = (homes: ReadonlyArray<TaxedHome>, rates: Rates, tier:
}
/** Actual collection rounding, not rounded ledger display values. */
-export const baseCollection = (taxes: number, upkeep: number, residents: number, rules: Rules = shippedRules) => {
+export const baseCollection = (taxes: number, upkeep: number, residents: number, rules: Rules = shippedRules, saves = 0) => {
const share = rules.ledgerTicks * rules.stepSeconds / 60
- const admin = adminOf(residents, rules)
+ const admin = adminOf(residents, rules, saves)
return { admin, delta: Math.round(taxes * share) - Math.round((upkeep + admin) * share) }
}
diff --git a/src/rules/upgrades.ts b/src/rules/upgrades.ts
new file mode 100644
index 0000000..f13d9db
--- /dev/null
+++ b/src/rules/upgrades.ts
@@ -0,0 +1,44 @@
+/**
+ * What an upgrade does, in words a mayor can weigh before paying for it:
+ * each thing about the building it changes, from what it is now to what it
+ * will be (see `asUpgraded`), and what it costs, now and carried in. The
+ * build menu, the upgrade tool's tooltip, and the building's panel all read
+ * these, so the mayor is told the same thing wherever they look.
+ */
+import { asUpgraded, costText, nextUpgrade, upgradeAt, type Kind, type Upgrade } from "../content.ts"
+import { shippedRules, type Rules } from "./config.ts"
+
+const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}`
+const seconds = (s: number) => `${Math.round(s * 10) / 10} s`
+
+/** What changes from `level` to the next, a line each ("upkeep 6 → 12 coins a minute"); empty when there is no next. */
+export const upgradeChanges = (kind: Kind, level: number, rules: Rules = shippedRules): ReadonlyArray<string> => {
+ const up = nextUpgrade(kind, level)
+ if (!up) return []
+ const now = asUpgraded(kind, level), then = asUpgraded(kind, level + 1), out: Array<string> = []
+ if (now.recipe && then.recipe && now.recipe.seconds !== then.recipe.seconds) {
+ const per = (k: Kind) => Math.round((60 / k.recipe!.seconds) * k.recipe!.batch)
+ out.push(`${rules.goods[now.recipe.output].title} ${per(now)} → ${per(then)} a minute (a job every ${seconds(now.recipe.seconds)} → ${seconds(then.recipe.seconds)})`)
+ }
+ if (now.workers !== then.workers) out.push(`workers ${now.workers} → ${then.workers}`)
+ if (now.holds && then.holds && now.holds.cap !== then.holds.cap) out.push(`holds ${now.holds.cap} → ${then.holds.cap} of each good`)
+ if (now.carriers !== then.carriers) out.push(`carriers ${now.carriers ?? 0} → ${then.carriers ?? 0}`)
+ if (now.service && then.service) {
+ if (now.service.range !== then.service.range) out.push(`walker reaches ${now.service.range} → ${then.service.range} road cells`)
+ if (now.service.seconds !== then.service.seconds) out.push(`a walker every ${seconds(now.service.seconds)} → ${seconds(then.service.seconds)}`)
+ }
+ const crewsNow = upgradeAt(kind, level)?.crews ?? (kind.service?.service === "fire" ? rules.risk.fire.crews : undefined)
+ if (up.crews !== undefined && up.crews !== crewsNow) out.push(`firefighters ${crewsNow ?? 0} → ${up.crews}`)
+ if (up.deep && !upgradeAt(kind, level)?.deep) out.push("cuts worked-out rock at full pace, not a third")
+ if (up.admin !== undefined) out.push(`administration ${Math.round((upgradeAt(kind, level)?.admin ?? 0) * 100)}% → ${Math.round(up.admin * 100)}% less`)
+ const a = now.appeal, b = then.appeal
+ if (b && (!a || a.value !== b.value || a.reach !== b.reach)) out.push(`desirability nearby ${a ? signed(a.value) : "0"} → ${signed(b.value)}${!a || a.reach !== b.reach ? `, out to ${b.reach} cells` : ""}`)
+ if (now.upkeep !== then.upkeep) out.push(`upkeep ${now.upkeep} → ${then.upkeep} coins a minute`)
+ return out
+}
+
+/** What starting an upgrade costs: coins now, and the materials carriers then bring ("400 coins now · carriers bring 6 planks, 12 stone"). */
+export const upgradePrice = (up: Upgrade): string => {
+ const carried = costText({ coins: 0, materials: up.cost.materials })
+ return `${up.cost.coins} coins now${carried ? ` · carriers bring ${carried}` : ""}`
+}
diff --git a/src/rules/worth.ts b/src/rules/worth.ts
index aef9542..c7a9729 100644
--- a/src/rules/worth.ts
+++ b/src/rules/worth.ts
@@ -8,9 +8,9 @@
* rules (or any candidate rules) to the bands these figures should keep.
* Plain functions over the rules: nothing here knows the ECS.
*/
-import { amounts, foods, goodIds, type GoodId, type Kind, type KindId, type Need, type Tier } from "../content.ts"
+import { amounts, asUpgraded, foods, goodIds, upgradeAt, type GoodId, type Kind, type KindId, type Need, type Tier } from "../content.ts"
import { shippedRules, type Rules } from "./config.ts"
-import { mealsOf, moreAdmin, taxOf } from "./households.ts"
+import { adminOf, mealsOf, moreAdmin, taxOf } from "./households.ts"
import { tradeCollection } from "./trade.ts"
const kindIds = (rules: Rules) => Object.keys(rules.kinds) as Array<KindId>
@@ -44,8 +44,8 @@ export interface ProducerWorth {
/** Jobs a minute a maker does with a full crew, a tool, and good repair. */
export const jobsPerMinute = (kind: Kind): number => (kind.recipe ? 60 / kind.recipe.seconds : 0)
-export const producerWorth = (id: KindId, rules: Rules = shippedRules): ProducerWorth => {
- const kind = rules.kinds[id], r = kind.recipe!, jobs = jobsPerMinute(kind)
+export const producerWorth = (id: KindId, rules: Rules = shippedRules, level = 0): ProducerWorth => {
+ const kind = asUpgraded(rules.kinds[id], level), r = kind.recipe!, jobs = jobsPerMinute(kind)
const out = jobs * r.batch * rules.goods[r.output].price
const inp = r.input ? jobs * r.inputs * rules.goods[r.input].price : 0
const tools = kind.wear ? (jobs / kind.wear) * rules.goods.tools.price : 0
@@ -224,17 +224,58 @@ export interface ServiceWorth {
readonly perUpkeep: number
}
-/** Every service building, and each upgraded one as its own entry. */
+/** Every service building, and each upgrade of one as its own entry. */
export const services = (rules: Rules = shippedRules): Array<ServiceWorth> =>
kindIds(rules).flatMap((id) => {
- const k = rules.kinds[id]
- if (!k.service || !k.buildable) return []
- const plain = { id, service: k.service.service, cost: costWorth(k.cost, rules), upkeep: k.upkeep, reach: (k.service.range * 60) / k.service.seconds }
- const out: Array<ServiceWorth> = [{ ...plain, perUpkeep: plain.reach / plain.upkeep }]
- if (k.upgrade?.service) {
- const up = { id: `${id}+${k.upgrade.title.toLowerCase()}`, service: k.service.service, cost: plain.cost + costWorth(k.upgrade.cost, rules), upkeep: k.upgrade.upkeep,
- reach: (k.upgrade.service.range * 60) / k.upgrade.service.seconds }
- out.push({ ...up, perUpkeep: up.reach / up.upkeep })
+ const base = rules.kinds[id]
+ if (!base.service || !base.buildable) return []
+ const out: Array<ServiceWorth> = []
+ let cost = costWorth(base.cost, rules)
+ for (let level = 0; level <= 2; level++) {
+ if (level > 0 && !upgradeAt(base, level)) break
+ if (level > 0) cost += costWorth(upgradeAt(base, level)!.cost, rules)
+ const k = asUpgraded(base, level), reach = (k.service!.range * 60) / k.service!.seconds
+ out.push({ id: level === 0 ? id : `${id}+${upgradeAt(base, level)!.title.toLowerCase()}`, service: k.service!.service, cost, upkeep: k.upkeep, reach, perUpkeep: reach / k.upkeep })
+ }
+ return out
+ })
+
+// ── Upgrades ──────────────────────────────────────────────────────────────
+
+export interface UpgradeWorth {
+ readonly id: string
+ readonly title: string
+ /** One-off: coins and materials. */
+ readonly cost: number
+ /** Coins a minute more it costs to keep. */
+ readonly upkeep: number
+ /** Coins a minute more it earns or saves (`null`: nothing the ledger can price, a walker or shelves). */
+ readonly gain: number | null
+ /** Minutes until what it earns, less its upkeep, has paid for it (`Infinity`: never). */
+ readonly payback: number | null
+}
+
+/**
+ * What each upgrade earns over what it was, at the usual prices: a
+ * workshop's value added, a masonry's from a third of its pace to all of
+ * it, a guildhall's or a city hall's administration saved for a town at its
+ * land's goal for that rank. A walker or shelves it cannot price.
+ */
+export const upgradeWorths = (rules: Rules = shippedRules, size: keyof Rules["sizes"] = "medium"): Array<UpgradeWorth> =>
+ [...kindIds(rules)].flatMap((id) => {
+ const base = rules.kinds[id], out: Array<UpgradeWorth> = []
+ for (let level = 1; level <= 2; level++) {
+ const up = upgradeAt(base, level)
+ if (!up) break
+ const before = asUpgraded(base, level - 1), cost = costWorth(up.cost, rules), upkeep = up.upkeep - before.upkeep
+ let gain: number | null = null
+ if (up.deep && base.recipe) gain = producerWorth(id, rules, level).adds * (2 / 3)
+ else if (base.recipe && base.buildable) gain = producerWorth(id, rules, level).adds - producerWorth(id, rules, level - 1).adds
+ else if (up.admin !== undefined) {
+ const goal = rules.sizes[size].goal.residents * (rules.ranks[up.rank + 1]?.residents ?? 1)
+ gain = adminOf(goal, rules) * (up.admin - (upgradeAt(base, level - 1)?.admin ?? 0))
+ }
+ out.push({ id: `${id}:${level}`, title: up.title, cost, upkeep, gain, payback: gain === null ? null : gain > upkeep ? cost / (gain - upkeep) : Infinity })
}
return out
})
diff --git a/src/save.ts b/src/save.ts
index 44e2e26..a6d9b15 100644
--- a/src/save.ts
+++ b/src/save.ts
@@ -30,7 +30,7 @@ export const SAVE_VERSION = 9
* done); from 7, its first term, and its rank: a town that was complete
* (or governed on after) is a town, any other a hamlet that rises as its
* goals hold. A complete town waiting on its mayor carries on playing;
- * from 8, its water as never fished.
+ * from 8, its water as never fished and its upgrades as the first.
* Anything else is left to the world's own validation.
*/
const carry = (version: number, world: unknown): unknown | null => {
@@ -38,10 +38,12 @@ const carry = (version: number, world: unknown): unknown | null => {
const w = world as { resources?: Record<string, unknown>; entities?: Array<{ components?: Record<string, unknown> }> }
const r = w.resources
if (!r || typeof r !== "object") return null
- // From 8, water that was never fished.
+ // From 8, water that was never fished, and an upgraded building upgraded once.
for (const e of Array.isArray(w.entities) ? w.entities : []) {
const water = e.components?.["Town/Water"]
if (water && typeof water === "object" && !("fished" in water)) e.components!["Town/Water"] = { fished: -1_000_000 }
+ const upgraded = e.components?.["Town/Upgraded"]
+ if (upgraded && typeof upgraded === "object" && !("level" in upgraded)) e.components!["Town/Upgraded"] = { level: 1 }
}
if (version === 8) return w
const fate = r["Town/Fate"] as Record<string, unknown> | undefined
diff --git a/src/schema.ts b/src/schema.ts
index d488fa1..c4642aa 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -101,8 +101,16 @@ export const TownHall = Descriptor.Tag("Town/TownHall")
export const Status = Descriptor.ConstructedComponent(Decode.literal(...statuses))("Town/Status")
/** Stopped by the town: no workers, a quarter of its upkeep. */
export const Paused = Descriptor.Tag("Town/Paused")
-/** Upgraded where it stands (see `Kind.upgrade`): its walker, desirability, and upkeep are the upgrade's. */
-export const Upgraded = Descriptor.Tag("Town/Upgraded")
+/** Upgraded where it stands, `level` times (see `Kind.upgrade`): it works as `asUpgraded` says. */
+export const Upgraded = Descriptor.ConstructedComponent(Decode.struct({ level: Decode.literal(1, 2) }))("Town/Upgraded")
+/**
+ * Being upgraded to `level` where it stands: its coins are paid, and these
+ * materials are still owed, out of `total`; carriers bring them while it
+ * goes on working, and builders put in `done` steps of work as they come,
+ * never ahead of what is in (see `WORKS_TICKS`). Once everything is in and
+ * worked, it stands upgraded.
+ */
+export const Works = Descriptor.ConstructedComponent(Decode.struct({ owed: amounts, total: integer, done: integer, level: Decode.literal(1, 2) }))("Town/Works")
/**
* Workers it needs, how many came (`apprentices` of them settlers standing
@@ -417,7 +425,7 @@ export const Game = Schema.bind(
Schema.fragment({
components: {
Tile, Road, Paved, Park, Ruin, Site, Rising, Tree, Rock, Water, Field, House, Rebuilt, Risk, Condition, Burning, Sick, Building, TownHall, Status,
- Paused, Upgraded, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Patrol, Figure, Route, Errand, Rescue, Roam
+ Paused, Upgraded, Works, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Patrol, Figure, Route, Errand, Rescue, Roam
},
resources: {
Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Guide, Appeal, Pantry, Fires,
diff --git a/src/sim/edits.ts b/src/sim/edits.ts
index 223c495..a18d7f7 100644
--- a/src/sim/edits.ts
+++ b/src/sim/edits.ts
@@ -8,11 +8,11 @@
*/
import { buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft } from "../archetypes.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
-import { amounts, builtCost, goodIds, RESERVE_MAX, TAX_STEPS, ticks, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"
+import { amounts, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, ticks, total, upgradeAt, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"
import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"
import { inside } from "../iso.ts"
import { generate } from "../mapgen.ts"
-import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Treasury, Ui, Upgraded } from "../schema.ts"
+import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Treasury, Ui, Upgraded, Works } from "../schema.ts"
import { salvageOf, salvageText } from "../rules/salvage.ts"
import { elapsed, rollWinters, termTicks, TileRead, useOf, write } from "./shared.ts"
import type { Rules as RuleInputs } from "../rules/config.ts"
@@ -54,6 +54,7 @@ export const ApplyEdits = Game.System(
building: Game.Query.read(Building),
service: Game.Query.optional(Service),
upgraded: Game.Query.optional(Upgraded),
+ works: Game.Query.optional(Works),
site: Game.Query.optional(Site),
rising: Game.Query.optional(Rising)
}
@@ -307,7 +308,7 @@ export const ApplyEdits = Game.System(
const built = queries.built.get(owner)
if (built.ok && (built.value.data.building.present || built.value.data.house.present)) {
const b = maybe(built.value.data.building)
- const s = salvageOf(b ? builtCost(kinds[b.kind], built.value.data.upgraded.present) : home.cost, maybe(built.value.data.site)?.owed ?? null, rules)
+ const s = salvageOf(b ? builtCost(kinds[b.kind], maybe(built.value.data.upgraded)?.level ?? 0) : home.cost, maybe(built.value.data.site)?.owed ?? null, rules)
if (s.fee > 0 && coins < s.fee) {
ui.toast(`Pulling it down costs ${s.fee} coins`)
break
@@ -397,34 +398,31 @@ export const ApplyEdits = Game.System(
break
}
case "upgrade": {
+ // The coins are paid now; carriers bring the materials while it goes on working (see `Works`).
if (!inside(edit.cell.x, edit.cell.y)) break
const id = entities.get(ownerAt(grid.value(), edit.cell.x, edit.cell.y))
const row = id === undefined ? undefined : queries.upgradable.get(id)
if (!row?.ok) break
const { data } = row.value
const kind = kinds[data.building.get().kind]
- const up = kind.upgrade
- if (!up || data.upgraded.present || data.site.present || data.rising.present) break
+ const level = maybe(data.upgraded)?.level ?? 0
+ const up = nextUpgrade(kind, level)
+ if (!up || data.works.present || data.site.present || data.rising.present) break
const blocked = upgradeBlock(up, resources.fate.get().rank, rules)
if (blocked) {
ui.toast(`${up.title} ${blocked}`)
break
}
- const short = afford(up.cost)
- if (short) {
- ui.toast(short)
+ if (coins < up.cost.coins) {
+ ui.toast("Not enough coins")
break
}
- pay(up.cost)
- take(up.cost.materials)
- const service = maybe(data.service)
- commands.insert(
- row.value.entity.id,
- Game.Command.entry(Upgraded, {}),
- ...(service && up.service ? [Game.Command.entry(Service, { ...service, interval: ticks(up.service.seconds), range: up.service.range })] : [])
- )
- write(resources.chronicle, t, `The ${kind.title.toLowerCase()} is now a ${up.title.toLowerCase()}.`)
- ui.toast(`${up.title} · −${up.cost.coins} coins`)
+ coins -= up.cost.coins
+ const owed = amounts(up.cost.materials)
+ commands.insert(row.value.entity.id, Game.Command.entry(Works, { owed, total: total(owed), done: 0, level: (level + 1) as 1 | 2 }))
+ const was = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()
+ write(resources.chronicle, t, `Works begin on the ${was}: it is to be a ${up.title.toLowerCase()}.`)
+ ui.toast(`${up.title} · −${up.cost.coins} coins · carriers bring ${costText({ coins: 0, materials: up.cost.materials })}`)
break
}
case "reserve":
diff --git a/src/sim/hazards.ts b/src/sim/hazards.ts
index f8cbd08..ee68360 100644
--- a/src/sim/hazards.ts
+++ b/src/sim/hazards.ts
@@ -13,7 +13,7 @@ import * as Random from "@typeonce/bevy-ts-math/Random"
import { appealGrid, appealAt, buildingSource, homeSource, landSource, parkSources, type AppealSource } from "../appeal.ts"
import { ruinDraft } from "../archetypes.ts"
-import { goodIds, risk, type GoodId } from "../content.ts"
+import { goodIds, risk, upgradeAt, type GoodId } from "../content.ts"
import { doors, nearest, pathTo, reach, useAt } from "../grid.ts"
import { counted, placeName, type Landmark } from "../places.ts"
import type { Point } from "../iso.ts"
@@ -46,7 +46,7 @@ export const Appraise = Game.System(
if (resources.time.get().tick % appeal.every !== 0 && resources.appeal.get().cells.length > 0) return
const sources: Array<AppealSource> = []
for (const { data } of queries.buildings.each()) {
- const s = buildingSource(data.building.get().kind, data.tile.get(), rules, data.upgraded.present)
+ const s = buildingSource(data.building.get().kind, data.tile.get(), rules, maybe(data.upgraded)?.level ?? 0)
if (s) sources.push(s)
}
for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get(), rules))
@@ -92,7 +92,7 @@ export const Hazards = Game.System(
blazes: Game.Query({ selection: { burning: Game.Query.write(Burning) } }),
landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
watches: Game.Query({
- selection: { tile: Game.Query.read(Tile), service: Game.Query.read(Service), staff: Game.Query.read(Staff) },
+ selection: { tile: Game.Query.read(Tile), service: Game.Query.read(Service), staff: Game.Query.read(Staff), upgraded: Game.Query.optional(Upgraded) },
without: [Site, Rising, Burning]
}),
crews: Game.Query({ selection: { rescue: Game.Query.read(Rescue), home: Game.Query.readRelation(WalkerOf) } }),
@@ -286,7 +286,9 @@ export const Hazards = Game.System(
const goal = doors(grid, target.data.tile.get())
let best: { readonly watch: (typeof watches)[number]; readonly roads: ReturnType<typeof reach>; readonly cell: Point; readonly distance: number } | null = null
for (const watch of watches) {
- if ((out.get(watch.entity.id) ?? 0) >= risk.fire.crews) continue
+ // A fire brigade sends more (see `Upgrade.crews`).
+ const crews = upgradeAt(kinds.firewatch, maybe(watch.data.upgraded)?.level ?? 0)?.crews ?? risk.fire.crews
+ if ((out.get(watch.entity.id) ?? 0) >= crews) continue
const starts = doors(grid, watch.data.tile.get())
if (starts.length === 0) continue
const roads = reach(grid, starts)
diff --git a/src/sim/headless.ts b/src/sim/headless.ts
index 65d27f1..1dbbba6 100644
--- a/src/sim/headless.ts
+++ b/src/sim/headless.ts
@@ -22,7 +22,7 @@ export interface Snapshot {
export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void; readonly rules?: RuleInputs } = {}) => {
const ui: UiValue = {
- tool: "select", placing: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [], guide: [],
+ tool: "select", placing: null, upgrading: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [], guide: [],
edits: [{ type: "newTown", charter }],
preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false,
view: "none", overlay: { key: "", cells: [] }, tints: new Map(), legend: null, flash: null,
diff --git a/src/sim/logistics.ts b/src/sim/logistics.ts
index 3160a0d..558af33 100644
--- a/src/sim/logistics.ts
+++ b/src/sim/logistics.ts
@@ -13,7 +13,7 @@ import { preferDelivery } from "../rules/transport.ts"
import { goodIds, provisions, type GoodId } from "../content.ts"
import { doors, nearest, pathTo, reach, key, type Reach } from "../grid.ts"
import type { Point } from "../iso.ts"
-import { Building, Burning, Carriers, Errand, Figure, Game, Rules, Grid, House, Appeal, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe } from "../schema.ts"
+import { Building, Burning, Carriers, Errand, Figure, Game, Rules, Grid, House, Appeal, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, Works, maybe } from "../schema.ts"
import { CELL_STEPS } from "./shared.ts"
/** The most a carrier takes at once. */
@@ -49,6 +49,7 @@ export const Dispatch = Game.System(
}),
homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Burning] }),
sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),
+ works: Game.Query({ selection: { tile: Game.Query.read(Tile), works: Game.Query.read(Works) }, without: [Burning] }),
errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })
},
resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), time: Game.System.readResource(Time) },
@@ -86,6 +87,12 @@ export const Dispatch = Game.System(
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) })
}
+ // An upgrade under way is building work too: its materials go before anyone's shelves.
+ for (const { entity, data } of queries.works.each()) {
+ const works = data.works.get()
+ const ds = doors(grid, data.tile.get())
+ for (const g of goodIds) if (works.owed[g] > 0) wants.push({ id: entity.id, doors: ds, good: g, site: true, want: () => works.owed[g] - inbound(entity.id, g) })
+ }
const sitesWant = new Set(wants.filter((w) => w.want() > 0).map((w) => w.good))
const rooms: Array<{ readonly id: Id; readonly doors: ReadonlyArray<Point>; readonly room: (g: GoodId) => number; readonly keeps: boolean }> = []
for (const { entity, data } of queries.wanting.each()) {
@@ -202,7 +209,7 @@ export const turnAround = (route: { readonly cells: ReadonlyArray<Point>; readon
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
+ * A carrier hands its crate over: to a site or an upgrade under way, 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.
*/
@@ -212,7 +219,8 @@ export const Deliver = Game.System(
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) } })
+ sites: Game.Query({ selection: { site: Game.Query.write(Site) } }),
+ works: Game.Query({ selection: { works: Game.Query.write(Works) } })
},
services: { rules: Game.System.service(Rules) }
},
@@ -244,8 +252,13 @@ export const Deliver = Game.System(
if (!arrived(route)) continue
let handed = 0
const site = queries.sites.get(target.value.entity.id)
+ const works = queries.works.get(target.value.entity.id)
const inventory = queries.inventories.get(target.value.entity.id)
- if (site.ok) {
+ if (works.ok && works.value.data.works.get().owed[errand.good] > 0) {
+ const w = works.value.data.works.get()
+ handed = Math.min(errand.count, w.owed[errand.good])
+ works.value.data.works.set({ ...w, owed: { ...w.owed, [errand.good]: w.owed[errand.good] - handed } })
+ } else 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 } })
diff --git a/src/sim/town.ts b/src/sim/town.ts
index e83e38f..72b5dc3 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -6,7 +6,7 @@ import { tradeCollection } from "../rules/trade.ts"
*/
import { appealAt, parkUpkeep } from "../appeal.ts"
import { doors, key, reach } from "../grid.ts"
-import { amounts, goodIds, upkeepOf, type GoodId } from "../content.ts"
+import { amounts, goodIds, upgradeAt, upkeepOf, type GoodId } from "../content.ts"
import { Appeal, Building, Burning, Census, Charter, Flow, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rebuilt, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, Upgraded, maybe } from "../schema.ts"
import { connected, elapsed, seasonAt } from "./shared.ts"
@@ -124,7 +124,7 @@ export const Collect = Game.System(
/** A closed home pays nothing and costs the town hall nothing. */
homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Paused] }),
buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused), upgraded: Game.Query.optional(Upgraded) }, without: [Site] }),
- halls: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [TownHall] }),
+ halls: Game.Query({ selection: { tile: Game.Query.read(Tile), upgraded: Game.Query.optional(Upgraded) }, with: [TownHall] }),
stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] }),
parks: Game.Query({ selection: { park: Game.Query.read(Park) } })
},
@@ -160,14 +160,16 @@ export const Collect = Game.System(
if (reached) taxes += taxOf(data.house.get(), policy, rules, appealAt(cells, tile.x, tile.y))
}
let upkeep = 0
- for (const { data } of queries.buildings.each()) upkeep += upkeepOf(kinds[data.building.get().kind], data.upgraded.present) * (data.paused.present ? PAUSED_UPKEEP : 1)
+ for (const { data } of queries.buildings.each()) upkeep += upkeepOf(kinds[data.building.get().kind], maybe(data.upgraded)?.level ?? 0) * (data.paused.present ? PAUSED_UPKEEP : 1)
for (const { data } of queries.parks.each()) upkeep += parkUpkeep(data.park.get(), rules)
- const admin = adminOf(residents, rules)
+ // A guildhall or a city hall runs the town for less (see `Upgrade.admin`).
+ const saves = (hall ? upgradeAt(kinds.townhall, maybe(hall.data.upgraded)?.level ?? 0)?.admin : undefined) ?? 0
+ const admin = adminOf(residents, rules, saves)
const stores = queries.stores.each()
const before = resources.treasury.get().coins
const traded = tradeCollection(stores.map(({ data }) => data.inventory.get()), policy, resources.market.get().prices,
- before + baseCollection(taxes, upkeep, residents, rules).delta, rules)
+ before + baseCollection(taxes, upkeep, residents, rules, saves).delta, rules)
// What changed hands, for the minute's flow of goods: bought less sold.
const moved: Partial<Record<GoodId, number>> = {}
for (const [i, row] of stores.entries()) {
diff --git a/src/sim/work.ts b/src/sim/work.ts
index ca4de9b..10845b2 100644
--- a/src/sim/work.ts
+++ b/src/sim/work.ts
@@ -8,7 +8,7 @@ import { wildTreeSpots, canSeedTree } from "../rules/land.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
import { fieldDraft, treeDraft } from "../archetypes.ts"
-import { amounts, crewOf, goodIds, ticks, total, type Amounts, type Crew } from "../content.ts"
+import { amounts, asUpgraded, crewOf, goodIds, ticks, total, upgradeAt, worksNeeded, type Amounts, type Crew } from "../content.ts"
/** The flow of goods is counted in slices this many seconds long, and the last `FLOW_SLICES` of them (a minute) are kept. */
const FLOW_SLICE = 10
@@ -16,7 +16,7 @@ const FLOW_SLICES = 6
const each = (f: (g: (typeof goodIds)[number]) => number): Amounts => Object.fromEntries(goodIds.map((g) => [g, f(g)])) as Amounts
import { around, doors, GridBuilder, key, ownerAt, reach, roadPrint, useAt } from "../grid.ts"
-import { Building, Burning, Charter, Chronicle, Errand, Flow, Roam, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Treasury, Tree, maybe, type Status as StatusValue, Water } from "../schema.ts"
+import { Building, Burning, Carriers, Charter, Chronicle, Errand, Flow, Roam, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Service, Site, Staff, Status, Stock, Storage, Tile, Time, Treasury, Tree, Upgraded, maybe, type Status as StatusValue, Water, Works } from "../schema.ts"
import { connected, elapsed, seasonAt, TileRead, useOf, write } from "./shared.ts"
import { assignWorkers, equipmentPace, effort, paced } from "../rules/production.ts"
@@ -144,6 +144,9 @@ export const CountStock = Game.System(
// ── Going up ──────────────────────────────────────────────────────────────
+/** How often a storage under works takes a crate for it from its own shelves. */
+const SELF_SUPPLY_TICKS = ticks(1)
+
/** Where a site's walls are once its materials are in: it goes on rising from here. */
export const SITE_SHARE = 0.35
@@ -152,14 +155,68 @@ export const Raise = Game.System(
{
queries: {
sites: Game.Query({ selection: { site: Game.Query.read(Site) } }),
- rising: Game.Query({ selection: { rising: Game.Query.write(Rising), status: Game.Query.optional(Status) } })
+ rising: Game.Query({ selection: { rising: Game.Query.write(Rising), status: Game.Query.optional(Status) } }),
+ works: Game.Query({
+ selection: {
+ works: Game.Query.write(Works),
+ building: Game.Query.read(Building),
+ staff: Game.Query.write(Staff),
+ recipe: Game.Query.optional(Recipe),
+ carriers: Game.Query.optional(Carriers),
+ service: Game.Query.optional(Service)
+ }
+ }),
+ /** A storage under works (the town hall, a warehouse): its own shelves. */
+ stocked: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage, Works] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ chronicle: Game.System.writeResource(Chronicle)
},
services: { rules: Game.System.service(Rules) }
},
- ({ queries, commands, services }) => {
+ ({ queries, resources, commands, services }) => {
const rules = services.rules
const { buildTicks: BUILD_TICKS } = rules
+ // An upgrade whose materials are all in stands upgraded: it works from here on as `asUpgraded` says,
+ // keeping what it holds and what it was in the middle of.
+ const tick = resources.time.get().tick
+ for (const { entity, data } of queries.works.each()) {
+ let works = data.works.get()
+ // A storage under works (the town hall) builds with what it holds itself, a crate at a time.
+ const shelves = queries.stocked.get(entity.id)
+ if (shelves.ok && tick % SELF_SUPPLY_TICKS === 0) {
+ const own = shelves.value.data.inventory.get()
+ const g = goodIds.find((g) => works.owed[g] > 0 && own.stock[g] > 0)
+ if (g) {
+ const n = Math.min(rules.transport.load, works.owed[g], own.stock[g])
+ shelves.value.data.inventory.set({ ...own, stock: { ...own.stock, [g]: own.stock[g] - n } })
+ works = { ...works, owed: { ...works.owed, [g]: works.owed[g] - n } }
+ data.works.set(works)
+ }
+ }
+ // Builders work on as the materials come in, never ahead of them.
+ const needed = worksNeeded(works.total, rules), allowed = needed * (1 - total(works.owed) / Math.max(1, works.total))
+ if (works.done < allowed) {
+ works = { ...works, done: works.done + 1 }
+ data.works.set(works)
+ }
+ if (total(works.owed) > 0 || works.done < needed) continue
+ const base = rules.kinds[data.building.get().kind], kind = asUpgraded(base, works.level)
+ commands.remove(entity.id, Works)
+ commands.insert(entity.id, Game.Command.entry(Upgraded, { level: works.level }))
+ data.staff.set({ ...data.staff.get(), needed: kind.workers })
+ const recipe = maybe(data.recipe), carriers = maybe(data.carriers), service = maybe(data.service)
+ if (recipe && kind.recipe) commands.insert(entity.id, Game.Command.entry(Recipe, { ...recipe, period: ticks(kind.recipe.seconds) }))
+ if (shelves.ok && kind.holds) shelves.value.data.inventory.set({ ...shelves.value.data.inventory.get(), cap: kind.holds.cap })
+ if (carriers && kind.carriers) commands.insert(entity.id, Game.Command.entry(Carriers, { count: kind.carriers }))
+ if (service && kind.service) commands.insert(entity.id, Game.Command.entry(Service, { ...service, interval: ticks(kind.service.seconds), range: kind.service.range }))
+ const was = (upgradeAt(base, works.level - 1)?.title ?? base.title).toLowerCase()
+ write(resources.chronicle, elapsed(resources.time.get(), resources.charter.get()), `The ${was} is now a ${upgradeAt(base, works.level)!.title.toLowerCase()}.`, true)
+ }
+
for (const { entity, data } of queries.sites.each()) {
if (total(data.site.get().owed) > 0) continue
commands.remove(entity.id, Site)
@@ -292,7 +349,8 @@ export const Work = Game.System(
status: Game.Query.write(Status),
gatherer: Game.Query.optional(Gatherer),
paused: Game.Query.optional(Paused),
- condition: Game.Query.optional(Condition)
+ condition: Game.Query.optional(Condition),
+ upgraded: Game.Query.optional(Upgraded)
},
without: [Site, Rising]
}),
@@ -338,7 +396,7 @@ export const Work = Game.System(
}
/** 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 => {
+ const gather = (source: "tree" | "stone" | "ore" | "field" | "water", tile: { x: number; y: number; size: number }, radius: number, deep = false): boolean => {
for (const c of around(tile, radius)) {
const use = useAt(grid, c.x, c.y)
const id = ownerAt(grid, c.x, c.y)
@@ -362,7 +420,13 @@ export const Work = Game.System(
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.ore !== (source === "ore")) continue
+ // A masonry cuts a worked face at full pace (see `Upgrade.deep`); anyone else waits for it.
+ if (r.amount <= 0) {
+ if (!deep) continue
+ used.add(id)
+ return true
+ }
// Quarried down, a rock stays as a worked face (see `FACE_TICKS`).
rock.data.rock.set({ ...r, amount: r.amount - 1 })
if (r.amount === 2 && ![...rocks().values()].some((o) => o !== rock && o.data.rock.get().ore === r.ore && o.data.rock.get().amount >= 2))
@@ -402,7 +466,8 @@ export const Work = Game.System(
let short = !fed
if (open && staff.assigned > 0 && recipe.progress === 0 && room && fed) {
- if (gatherer && !gather(gatherer.source, tile, gatherer.radius)) short = true
+ const deep = upgradeAt(kind, maybe(data.upgraded)?.level ?? 0)?.deep ?? false
+ if (gatherer && !gather(gatherer.source, tile, gatherer.radius, deep)) short = true
else {
if (recipe.input !== null) stock = { ...stock, [recipe.input]: stock[recipe.input] - recipe.inputs }
recipe = { ...recipe, progress: 1 }
diff --git a/src/ui.ts b/src/ui.ts
index c6a69ed..c99bcdc 100644
--- a/src/ui.ts
+++ b/src/ui.ts
@@ -52,7 +52,7 @@ export interface Alert {
readonly places?: Partial<Record<KindId, { readonly at: Point; readonly size: number; readonly id: number }>>
}
-export type Tool = "select" | "road" | "pave" | "home" | "bulldoze" | "place" | "ground" | "prop"
+export type Tool = "select" | "road" | "pave" | "home" | "bulldoze" | "place" | "ground" | "prop" | "upgrade"
/** What the map shows over the town: nothing, or one of its views, cell by cell. */
export const viewIds = ["none", "appeal", "workers", "fire", "health", "order", "condition"] as const
@@ -141,9 +141,26 @@ export type Panel =
/** What pulling it down costs and gives back: "pull down: −25 coins · 2 planks back". */
readonly salvage: string
readonly groups: ReadonlyArray<Group>
- /** Whether it is upgraded; and the upgrade it could have, what it costs, and what keeps it from it now (`null`: nothing). */
+ /** What it is called and what it is for, at its level of upgrades (a market hall, not a market). */
+ readonly title: string
+ readonly blurb: string
+ /** Upgrades it has had (see `Kind.upgrade`), and whether it has had any. */
+ readonly level: number
readonly upgraded: boolean
- readonly upgrade: { readonly title: string; readonly cost: string; readonly blocked: string | null } | null
+ /**
+ * The upgrade it could have next (`null`: none, or one under way): what it becomes, what it costs
+ * now and carried in, what changes, and what keeps it from it now (the rank; coins short).
+ */
+ readonly upgrade: {
+ readonly title: string
+ readonly blurb: string
+ readonly price: string
+ readonly changes: ReadonlyArray<string>
+ readonly blocked: string | null
+ readonly short: string | null
+ } | null
+ /** An upgrade under way: what it is to become, the share of its materials in, and what is still owed. */
+ readonly works: { readonly title: string; readonly share: number; readonly left: string } | null
}
| {
readonly type: "house"
@@ -307,6 +324,25 @@ export interface Stats {
readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string; readonly alarm: boolean; readonly at: Point | null }>
/** What needs looking at right now, a line each: workshops waiting, workplaces no one can reach, food running out. */
readonly alerts: ReadonlyArray<Alert>
+ /**
+ * The upgrades the town could make, one for each kind and level (a market to a market hall; the town
+ * hall to a guildhall, or a guildhall to a city hall): what it becomes, what it costs now and carried
+ * in, what changes, what keeps it from it (the rank), and how many buildings are ready for it and under way.
+ */
+ readonly upgrades: ReadonlyArray<{
+ readonly kind: KindId
+ readonly level: number
+ readonly from: string
+ readonly to: string
+ readonly blurb: string
+ readonly coins: number
+ readonly materials: Partial<Record<GoodId, number>>
+ readonly price: string
+ readonly changes: ReadonlyArray<string>
+ readonly blocked: string | null
+ readonly ready: number
+ readonly underway: number
+ }>
/** The mayor's guide: the step to take now (if any, and the guide is on), and how far along it is. */
readonly guide: {
readonly step:
@@ -345,8 +381,9 @@ export interface Legend {
export interface UiValue {
tool: Tool
- /** The kind being placed with the `place` tool. */
+ /** The kind being placed with the `place` tool, and the kind whose buildings the `upgrade` tool upgrades. */
placing: KindId | null
+ upgrading?: KindId | null
/** The ground laid with the `ground` tool, and the furnishing set with the `prop` tool. */
ground: GroundId
prop: PropId
diff --git a/test/economy.test.ts b/test/economy.test.ts
index 7a457f8..a1bef87 100644
--- a/test/economy.test.ts
+++ b/test/economy.test.ts
@@ -13,11 +13,11 @@
*/
import assert from "node:assert/strict"
import { test } from "node:test"
-import { amounts, type GoodId, type GroundId, type Need, type PropId } from "../src/content.ts"
+import { amounts, type GoodId, type GroundId, type KindId, type Need, type PropId } from "../src/content.ts"
import { appealGrid, parkSources, parksOf, type ParkCell } from "../src/appeal.ts"
import { shippedRules } from "../src/rules/config.ts"
import { moreAdmin, tierFor } from "../src/rules/households.ts"
-import { chainWorth, crownMargin, dominates, homes, median, openingKit, producers, services } from "../src/rules/worth.ts"
+import { chainWorth, crownMargin, dominates, homes, median, openingKit, producers, producerWorth, services, upgradeWorths } from "../src/rules/worth.ts"
import { district } from "../tools/balance/scenario.ts"
import { component, fixture } from "../tools/balance/verify/fixture.ts"
@@ -140,6 +140,23 @@ test("a bigger building for a service walks at least as far for its upkeep as a
none(out, "a dearer service building does less a coin")
})
+// ── Upgrades ──────────────────────────────────────────────────────────────
+
+/** Minutes an upgrade that earns should take to pay for itself: never at once, and within a term. */
+const UPGRADE_PAYBACK = [2, 45] as const
+
+test("every upgrade that earns pays for itself within a term, never at once", () => {
+ none(upgradeWorths(rules).filter((u) => u.payback !== null && (u.payback < UPGRADE_PAYBACK[0] || u.payback > UPGRADE_PAYBACK[1]))
+ .map((u) => `${u.title}: costs ${u.cost}, earns ${round(u.gain!)}/min for ${u.upkeep} more upkeep, pays back in ${round(u.payback!)} min`), "upgrade out of the band")
+})
+
+test("an upgraded producer still adds about what producers usually do for its upkeep", () => {
+ const usual = median(producers(rules).map((p) => p.perUpkeep))
+ const upgraded = (Object.keys(rules.kinds) as Array<KindId>).filter((id) => rules.kinds[id].recipe && rules.kinds[id].upgrade && !rules.kinds[id].upgrade!.deep)
+ none(upgraded.map((id) => producerWorth(id, rules, 1)).filter((p) => p.perUpkeep < usual * PRODUCER_BAND[0] || p.perUpkeep > usual * PRODUCER_BAND[1])
+ .map((p) => `${p.id} upgraded: ×${round(p.perUpkeep / usual)} of the usual`), "upgraded producer outside the band")
+})
+
// ── Parks ─────────────────────────────────────────────────────────────────
/** The most a park of one cell gives: no more than a street or a little more. */
diff --git a/test/endless.test.ts b/test/endless.test.ts
index 0209aff..845c43c 100644
--- a/test/endless.test.ts
+++ b/test/endless.test.ts
@@ -74,7 +74,7 @@ test("a rock quarried down stays as a worked face, and gives one more now and th
assert(after.every((e) => e.components["Town/Rock"].amount === 1))
})
-test("a market is upgraded to a market hall once the town is a town, and not before", () => {
+test("a market is upgraded to a market hall once the town is a town, and not before: paid now, built as carriers bring its materials", () => {
const toasts: Array<string> = []
const t = headless(charter, { toast: (m) => toasts.push(m) })
t.run(1)
@@ -86,24 +86,60 @@ test("a market is upgraded to a market hall once the town is a town, and not bef
t.run(1)
const hamlet = t.snapshot().entities.find((e) => e.components["Town/Building"]?.kind === "market")!
assert.equal("Town/Upgraded" in hamlet.components, false)
+ assert.equal("Town/Works" in hamlet.components, false)
assert(toasts.some((m) => m.includes("needs the town to be a town")), toasts.join(" | "))
t.change((s) => {
s.resources["Town/Fate"].rank = 2
})
- const stone = stockOf(t.snapshot(), "stone")
+ const up = kinds.market.upgrade!
+ const coins = t.snapshot().resources["Town/Treasury"].coins, stone = stockOf(t.snapshot(), "stone")
t.edit({ type: "upgrade", cell })
t.run(1)
+ const begun = t.snapshot(), works = begun.entities.find((e) => e.components["Town/Building"]?.kind === "market")!
+ // The coins go at once; the materials are owed and then worked in, and the market works on meanwhile.
+ assert(begun.resources["Town/Treasury"].coins <= coins - up.cost.coins)
+ assert("Town/Works" in works.components, toasts.join(" | "))
+ assert.equal(works.components["Town/Works"].total, Object.values(up.cost.materials).reduce((n, k) => n + k!, 0))
+ assert.equal("Town/Upgraded" in works.components, false)
+ assert.equal(works.components["Town/Service"].range, kinds.market.service!.range)
+ assert(begun.resources["Town/Chronicle"].lines.some((l: { text: string }) => l.text === "Works begin on the market: it is to be a market hall."))
+ t.run(90)
const s = t.snapshot()
const hall = s.entities.find((e) => e.components["Town/Building"]?.kind === "market")!
- const up = kinds.market.upgrade!
- assert.equal("Town/Upgraded" in hall.components, true)
+ assert.equal("Town/Works" in hall.components, false, JSON.stringify(hall.components["Town/Works"]))
+ assert.deepEqual(hall.components["Town/Upgraded"], { level: 1 })
assert.equal(hall.components["Town/Service"].range, up.service!.range)
assert.equal(hall.components["Town/Service"].interval, ticks(up.service!.seconds))
- assert.equal(stockOf(s, "stone"), stone - up.cost.materials.stone!)
+ assert(stockOf(s, "stone") <= stone - up.cost.materials.stone!)
assert(s.resources["Town/Chronicle"].lines.some((l: { text: string }) => l.text === "The market is now a market hall."))
})
+test("the town hall becomes a guildhall from its own stores, and the guildhall a city hall", () => {
+ const t = headless(charter)
+ t.run(1)
+ const hallOf = (s: Snapshot) => s.entities.find((e) => e.components["Town/TownHall"])!
+ let cell = { x: 0, y: 0 }
+ t.change((s) => {
+ s.resources["Town/Fate"].rank = 2
+ s.resources["Town/Treasury"].coins = 5000
+ const hall = hallOf(s)
+ cell = hall.components["Town/Tile"]
+ hall.components["Town/Inventory"].stock = { ...hall.components["Town/Inventory"].stock, planks: 90, stone: 140, tools: 30, cloth: 30 }
+ })
+ t.edit({ type: "upgrade", cell })
+ t.run(150)
+ const guild = hallOf(t.snapshot())
+ assert.deepEqual(guild.components["Town/Upgraded"], { level: 1 }, JSON.stringify(guild.components["Town/Works"]))
+ assert.equal(guild.components["Town/Inventory"].cap, kinds.townhall.upgrade!.cap)
+ assert.equal(guild.components["Town/Carriers"].count, kinds.townhall.upgrade!.carriers)
+ t.edit({ type: "upgrade", cell })
+ t.run(300)
+ const city = hallOf(t.snapshot())
+ assert.deepEqual(city.components["Town/Upgraded"], { level: 2 }, JSON.stringify(city.components["Town/Works"]))
+ assert.equal(city.components["Town/Inventory"].cap, kinds.townhall.upgrade!.next!.cap)
+})
+
test("once a term runs out, the next one carries on the same town", () => {
const t = headless(charter)
t.run(1)
@@ -201,7 +237,8 @@ test("pulling down a market hall gives back part of the upgrade too", () => {
s.resources["Town/Fate"].rank = 2
})
t.edit({ type: "upgrade", cell })
- t.run(1)
+ t.run(90)
+ assert.deepEqual(t.snapshot().entities.find((e) => e.components["Town/Building"]?.kind === "market")!.components["Town/Upgraded"], { level: 1 })
const stone = stockOf(t.snapshot(), "stone")
t.edit({ type: "remove", cell })
t.run(1)
diff --git a/test/render3d.test.ts b/test/render3d.test.ts
index 0963e8c..26e6690 100644
--- a/test/render3d.test.ts
+++ b/test/render3d.test.ts
@@ -1,9 +1,11 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import * as THREE from "three"
-import { kindIds } from "../src/content.ts"
+import { kindIds, kinds } from "../src/content.ts"
+import { U } from "../src/iso.ts"
+import { dressed } from "../src/asset-lab/upgrade-dress.ts"
import { Drawing, type InkAsset } from "../src/asset-lab/primitives.ts"
-import { buildingAsset, buildingHeight, homeAsset, noDoors, treeVariant } from "../src/render3d/models.ts"
+import { buildingAsset, buildingHeight, buildingTop, homeAsset, noDoors, scaffoldAsset, treeVariant } from "../src/render3d/models.ts"
import { upgradeHeights } from "../src/asset-lab/service-upgrades.ts"
import { ModelHandle, ModelPool } from "../src/render3d/pool.ts"
import { assetById } from "../src/asset-lab/assets.ts"
@@ -35,12 +37,12 @@ test("live service upgrades retain their taller models and material bounds besid
for (const id of ["market", "chapel"] as const) for (const side of Object.keys(noDoors)) {
const doors = { ...noDoors, [side]: true }
const base = buildingAsset(id, 1, null, doors, 1)
- const upgraded = buildingAsset(id, 1, null, doors, 1, { winter: true }, true)
+ const upgraded = buildingAsset(id, 1, null, doors, 1, { winter: true }, 1)
valid(upgraded)
assert.equal(upgraded.reference?.type === "building" && upgraded.reference.tier, 2)
const top = (asset: InkAsset) => Math.max(...asset.faces.flatMap(face => face.points.map(p => p[2])))
assert.ok(top(upgraded) > top(base), `${id}/${side}: live upgrade lost its silhouette`)
- assert.equal(buildingHeight(id, true), upgradeHeights[id].eave)
+ assert.equal(buildingHeight(id, 1), upgradeHeights[id].eave)
assert.equal(upgraded.effects?.height, upgradeHeights[id].eave)
assert.equal(upgraded.effects?.state.snow, 1)
}
@@ -48,6 +50,33 @@ test("live service upgrades retain their taller models and material bounds besid
assert.equal(buildingHeight(id), height, `${id}: public height must follow the revised model`)
})
+test("every other upgrade keeps its building's own model, adds to it inside its plot, and stands taller", () => {
+ for (const id of dressed) for (const level of id === "townhall" ? [1, 2] : [1]) {
+ const doors = { ...noDoors, right: true }
+ const base = buildingAsset(id, 1, null, doors, 1), up = buildingAsset(id, 1, null, doors, 1, {}, level)
+ valid(up)
+ const plot = kinds[id].size * 8 * U + 1e-9
+ const reach = (asset: InkAsset) => Math.max(...[...asset.faces.flatMap((f) => f.points), ...asset.strokes.flatMap((s) => s.points)].map((p) => Math.max(Math.abs(p[0]), Math.abs(p[1]))))
+ assert.ok(reach(up) <= plot, `${id}/${level}: the upgrade reaches past its plot (${reach(up)} > ${plot})`)
+ assert.ok(up.faces.length + up.strokes.length > base.faces.length + base.strokes.length, `${id}/${level}: nothing is added`)
+ assert.ok(buildingTop(id, level) >= buildingTop(id, 0), `${id}/${level}: its marker sinks`)
+ }
+})
+
+test("scaffolding stays inside the plot and rises with the materials in", () => {
+ for (const size of [2, 3]) {
+ const plot = size * 8 * U + 1e-9
+ const top = (asset: InkAsset) => Math.max(...asset.strokes.flatMap((s) => s.points.map((p) => p[2])))
+ const some = scaffoldAsset(size, 32, 0.2), most = scaffoldAsset(size, 32, 0.9)
+ for (const asset of [some, most]) {
+ valid(asset)
+ assert.ok(Math.max(...asset.strokes.flatMap((s) => s.points.map((p) => Math.max(Math.abs(p[0]), Math.abs(p[1]))))) <= plot)
+ }
+ assert.ok(most.strokes.length > some.strokes.length, "more boards as more comes in")
+ assert.ok(top(most) >= top(some))
+ }
+})
+
test("shared geometry retains independent colours, transforms and entity picking", () => {
const pool = new ModelPool(), root = new THREE.Group()
let built = 0