A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Finish the town that goes on: the crown's tally per term, the upgrade models in town, worked faces drawn and cleared
SandroMaglionef24ae0ece39e
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex 2b1f222..71f6879 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -68,7 +68,7 @@ the cache of unused animation/construction states. Loading or founding atown clears and rebuilds the presentation from the saved world.`pnpm check:browser` uses an isolated Chromium browser and the running dev-server. It can use installed Brave/Chrome or `BROWSER_EXECUTABLE_PATH`; otherwise+server (start `pnpm dev` first; without one it times out loading the page). It can use installed Brave/Chrome or `BROWSER_EXECUTABLE_PATH`; otherwiseinstall Chromium with `pnpm exec playwright install chromium`. `GAME_BASE_URL`overrides the local URL. It generates a reproducible 20-minute bot save,loads it through the real UI, and writes screenshots and measurements to@@ -99,12 +99,12 @@ and elevation controls also work with a keyboard. The original view uses a| --- | ---: | --- || Buildings | 39 | Every building kind, tier 2 market hall and church, plus winter and worn material presets of the seven town services and stores || Homes | 21 | Four settler and citizen roof palettes, townhouse, and fine/poor/worn/winter material presets of every tier |-| Land | 30 | Trees, single-cell rocks and larger outcrops, crops, roads, water, raised stone paving, three retained park furnishings and the park layout |+| Land | 32 | Trees, single-cell rocks (full, quarried, and worked down to a face) and larger outcrops, crops, roads, water, raised stone paving, three retained park furnishings and the park layout || People | 32 | Carriers, residents, market and chapel walkers, and five equipped service workers || Cargo and vehicles | 75 | Twelve distinct goods and labelled crates; empty handcart/barrow and small/full loads of each good; the approved mixed goods plate || Construction and effects | 14 | Sites, frame/walls, problem sign, smoke, placement outlines and three kinds of ruin |-The 211 entries cover object families and representative seeded variants.+The 213 entries cover object families and representative seeded variants.Continuous growth, construction progress, walk poses and colours can begenerated; this is not a list of every possible random seed. Page iconsremain the game's original 2D UI art.@@ -114,10 +114,11 @@ remain the game's original 2D UI art.[`/service-upgrades.html`](http://localhost:5232/service-upgrades.html) comparesthe market with the market hall and the chapel with the church. The fourmodels share one scale and synchronized rotation, tilt and zoom. Each model-has a GLB download. [The integration handoff](docs/service-upgrade-assets.md)-describes the asset API and the gameplay work still needed.+has a GLB download. [The asset notes](docs/service-upgrade-assets.md)+describe the asset API and how the town draws them: an upgraded building is+drawn with its tier 2 model, turned a quarter at a time to face its road.-`pnpm assets:build` exports 211 GLBs and editable geometry descriptions,+`pnpm assets:build` exports 213 GLBs and editable geometry descriptions,a manifest, and six standalone viewers to `output/inkline-3d/`:`inkline-3d-study.html`, `inkline-3d-map.html`, and`inkline-town-model-review.html`, `inkline-house-effects.html`, `inkline-park.html`, and `inkline-service-upgrades.html`. It reimports every GLB and@@ -207,8 +208,9 @@ That is how the README's screenshots of grown towns were made.Open [`/model-review.html`](http://localhost:5232/model-review.html) forthe models added for PR #3. Collections cover buildings, parks,-home tiers and neighbourhoods, winter, hazards, people/cargo and building-condition. Drag any model or use the rotation slider to turn the collection.+home tiers and neighbourhoods, winter, hazards, people/cargo, building+condition, and upgrades & worked faces (the market and chapel beside their+upgrades, and stone and ore full, quarried, and worked down to a face). Drag any model or use the rotation slider to turn the collection.**Inspect** opens the full asset viewer. **Download GLB** exports one model;**Save model sheet** captures a labelled sheet of the selected collection.`pnpm check:models` checks every collection, camera controls, sheet exports@@ -286,6 +288,12 @@ pnpm balance -- --seeds 1 --verbose --every 1 # minute by minutepnpm balance -- --snapshot 40 # save each seed's town at minute 40 (see above)```+Each seed reports the ranks it rose to and when, and the summary how many+seeds reached each rank and around which minute. On a medium fair 90-minute+term the sensible bot reaches the village around minute 24 (the citizens'+share holds it back) and the town around minute 36; it builds no parks and+makes no upgrades, so it does not reach the city.+The economy is tuned so that spreading cottages stops paying: food goes by theresident, administration per home climbs (each more home costs about 6 coins aminute at 80 homes), taxes above 100% empty homes directly, and bought goods@@ -356,9 +364,12 @@ always make the same town. `RUNS=200 pnpm test` searches harder;`test/endless.test.ts` checks the town that goes on, each in seconds of gametime: each rank asks more than the last, a rock quarried down stays as a-worked face and gives one more now and then, a market becomes a market hall-only once the town is a town, and the next term carries on the same town with-its own winters.+worked face and gives one more now and then (and the bulldozer clears only a+worked face), a market becomes a market hall only once the town is a town+(and pulling one down gives back part of both costs), the next term carries+on the same town with its own winters, and a long reign of five terms ends+each on time, starts the crown's tally afresh each term, thins its older+history, keeps its chronicle capped, and keeps its save in bounds.`test/share.test.ts` checks the server's routes and what they refuse, andcarries a real town through them into another headless town, which mustdiff --git a/README.md b/README.mdindex 505a2a4..6149d00 100644--- a/README.md+++ b/README.md@@ -98,7 +98,7 @@ A town is founded as a hamlet. Hold every goal of the next rank for twominutes (enough people and coins, a share of them citizens, a town thatapproves 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 the town can upgrade its market to a+brings a reward from the crown, and a town can upgrade its market to amarket hall and its chapel to a church. Nothing ends when a rank isreached.@@ -107,7 +107,7 @@ three of the crown's requests ignored, and the term is **lost**. Otherwisetime runs out and the term is judged: flourishing, holding on, or declining.Stand for the **next term** to carry on the same town, or retire and found anew one. The open stone and ore run out, but the worked faces they leave keep-giving a little, so a long reign never runs dry.+giving a little, so a long reign never runs dry (or clear them to build).The reckoning shows how the term went: residents, coins, and approvalacross it, with the winters shaded, and the chronicle of everything thatdiff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 652349b..f080ef1 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -67,7 +67,8 @@ six months.more for it every minute; the open stone and ore are quarried down toworked faces, which give one more every 90 seconds, so a quarry or minebeside them goes on at about a third of its pace (the chronicle says- when the last open rock is gone);+ when the last open rock is gone); the bulldozer clears a worked face+ for building, and it gives nothing more;- *approval*, from -100 to 100, follows needs met, taxes, unpaid wages,snubs from the crown, and hungry winters, and decides how many peopleeach home holds. Taxes above 100% also send residents away directly,@@ -90,10 +91,11 @@ six months.townhouses). Hold every goal of the next rank for two minutes and the townrises: 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 a city- its chapel into a *church*, where they stand (the building's panel):+- **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 furtherand more often, the street around it is finer, and the upkeep is higher.+ Pulling one down gives back part of what both cost.- **The end of a term**: it is *lost* to bankruptcy (three minutes indebt), revolt (approval at -50 or below for two minutes), abandonment(people fall below 15% of their peak), or dismissal (three of the crown'sdiff --git a/docs/service-upgrade-assets.md b/docs/service-upgrade-assets.mdindex f352403..20985cc 100644--- a/docs/service-upgrade-assets.md+++ b/docs/service-upgrade-assets.md@@ -1,8 +1,8 @@# Market hall and church assetsThe tier 2 presentation assets are approved, including the church's straight-sided-timber double door. They are registered in the catalogue and review map. Gameplay-still selects the original tier 1 buildings.+timber double door. They are registered in the catalogue and review map, and+the town draws them once a market or chapel is upgraded (see `Kind.upgrade`).## Asset API@@ -21,19 +21,23 @@ existing service family. Asset IDs are `market-hall` and `church`.These functions currently build complete preview assets, including plates. Liveintegration should support the existing `BuildingOptions` conventions forroad-facing doors, construction fitting, plate visibility and separate motion.-Do not replace `buildingAsset()` with the preview helper without those controls.--## Gameplay integration still needed--- Define upgrade eligibility, costs and service effects. Persist a service tier- with a backward-compatible tier 1 default for existing saves.-- Pass tier through presentation to `src/render3d/models.ts` and- `src/render3d/views.ts`; include it in shared model/cache keys. Preserve the- current condition, winter, smoke and construction behavior.-- Use the upgraded silhouette and dimensions for construction and effects.- Keep the chapel's original cupola and market's original flag on tier 1.-- Add upgrade UI and verify save/load, construction, road-facing entrances,- selection and rotation. Asset metadata alone does not activate upgrades.+Do not replace `buildingAsset()` with the preview help## In the town++`buildingAsset(id, …, upgraded)` in `src/render3d/models.ts` draws an+upgraded market or chapel with `serviceBuilding(kind, 2, { plate: false, doors })`.+The town draws plates apart, so the model leaves its own out. The model turns a+quarter at a time (`quartersFor`) to put the most of its street fronts on the+roads at its doors: the market hall's two arcades, the church's tower door.+The light stays baked from the same side: a lit wall that turns to face a+shaded side takes its material's shaded colour. `upgradeHeights` gives each+model's eaves (for surface effects and fire) and its top (for the problem+marker). The market hall drops the market's flag. The model cache key includes+the tier.++The panel's picture of a building is still the 2D drawing of the tier 1+building.++oes not activate upgrades.## Review and exportdiff --git a/scripts/balance.ts b/scripts/balance.tsindex 508dc25..657c3e1 100644--- a/scripts/balance.ts+++ b/scripts/balance.ts@@ -141,7 +141,7 @@ interface World {readonly policy: { readonly settlers: number; readonly citizens: number; readonly sells: ReadonlyArray<GoodId>; readonly buys: ReadonlyArray<GoodId>; readonly reserve: number }readonly mood: { readonly approval: number; readonly target: number }readonly crown: { readonly open: boolean; readonly good: GoodId; readonly amount: number; readonly met: number; readonly missed: number }- readonly fate: { readonly state: string; readonly reason: string; readonly at: number; readonly score: number; readonly goalSince: number }+ readonly fate: { readonly state: string; readonly reason: string; readonly at: number; readonly score: number; readonly goalSince: number; readonly rank: number }readonly charter: { readonly size: CharterValue["size"]; readonly term: number; readonly founded: number }readonly tick: number}@@ -662,6 +662,8 @@ const resting = new Map<KindId, number>()interface Row {readonly minute: number+ /** The town's rank (see `ranks`) at this minute. */+ readonly rank: numberreadonly coins: numberreadonly net: numberreadonly income: number@@ -772,13 +774,14 @@ const run = (seed: number) => {burning: w.census.burning!,lost: ruined.size,burghers: w.census.burghers!,+ rank: w.fate.rank,problems: problemsNow})}if (process.env.CHRONICLE) for (const l of town.snapshot().resources["Town/Chronicle"].lines as Array<{ tick: number; text: string }>) console.log(` ${(l.tick / 3600).toFixed(1)} ${l.text}`)const lastGoals = goalsOf(w.charter, {settlers: w.census.settlers!, citizens: w.census.citizens!, coins: w.coins, net: net(w), approval: w.mood.approval- }, rules).map((g) => `${g.met ? "✓" : "✗"} ${g.text} (${g.value})`).join(" · ")+ }, rules, w.fate.rank).map((g) => `${g.met ? "✓" : "✗"} ${g.text} (${g.value})`).join(" · ")const hh = Math.max(1, w.homes.length)console.log(` longest continuous goal hold: ${longestGoalHold.toFixed(1)} seconds`)const supplied = `food ${Math.round((w.census.food! / hh) * 100)}% bread ${Math.round((w.census.bread! / hh) * 100)}% cloth ${Math.round((w.census.cloth! / hh) * 100)}% faith ${Math.round((w.census.faith! / hh) * 100)}%`@@ -786,7 +789,12 @@ const run = (seed: number) => {const built: Record<string, number> = {}for (const b of w.buildings) built[b.kind] = (built[b.kind] ?? 0) + 1const final = town.snapshot().resources- return { seed, rows, problems, end, score: w.fate.score, built, stock: w.stock, crown: w.crown, lastGoals, supplied, lost: ruined.size,+ // The ranks the town rose to, and the first minute it stood at each.+ const risen = rules.ranks.slice(1).flatMap((r, i) => {+ const row = rows.find((x) => x.rank >= i + 1)+ return row ? [{ title: r.title, minute: row.minute }] : []+ })+ return { seed, rows, problems, end, score: w.fate.score, built, stock: w.stock, crown: w.crown, lastGoals, supplied, lost: ruined.size, risen,longestGoalHoldSeconds: longestGoalHold,final: { census: final["Town/Census"], treasury: final["Town/Treasury"], ledger: final["Town/Ledger"], mood: final["Town/Mood"], fate: final["Town/Fate"], charter: final["Town/Charter"] } }}@@ -809,7 +817,7 @@ const play = (which: Bot) => {results.push(r)const outcome = r.end.state === "playing" ? "still playing" : `${r.end.state} at ${r.end.minute} min: ${r.end.reason}`console.log(`seed ${r.seed}: ${outcome} (score ${r.score})`)- console.log(` goals: ${r.lastGoals}`)+ console.log(` ranks: ${r.risen.length ? r.risen.map((x) => `${x.title} at ${x.minute} min`).join(", ") : "still a hamlet"} · next: ${r.lastGoals}`)console.log(` homes supplied: ${r.supplied} · built ${Object.entries(r.built).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")}`)if (verbose) {console.log(header)@@ -828,6 +836,9 @@ const play = (which: Bot) => {;(outcomes[k] ??= []).push(r.end.minute)}console.log(` outcomes ${Object.entries(outcomes).map(([k, ms]) => `${k} ×${ms.length} (around minute ${Math.round(mean(ms))})`).join(", ")}`)+ const reached: Record<string, Array<number>> = {}+ for (const r of results) for (const x of r.risen) (reached[x.title] ??= []).push(x.minute)+ console.log(` ranks ${Object.entries(reached).map(([k, ms]) => `${k} ×${ms.length} (around minute ${Math.round(mean(ms))})`).join(", ") || "none reached"}`)console.log(` score ${Math.round(mean(results.map((r) => r.score)))}`)console.log(` crown met ${mean(results.map((r) => r.crown.met)).toFixed(1)}, missed ${mean(results.map((r) => r.crown.missed)).toFixed(1)}`)// The pressure curve: each checkpoint averaged over the seeds still running then.diff --git a/scripts/check-town-models.ts b/scripts/check-town-models.tsindex 759c2da..f8973f8 100644--- a/scripts/check-town-models.ts+++ b/scripts/check-town-models.ts@@ -14,7 +14,7 @@ page.on("console", e => { if (e.type() === "error") errors.push(e.text()) })page.on("response", r => { if (r.status() >= 400) errors.push(`${r.status()} ${r.url()}`) })const output = "output/inkline-3d/town-review"await mkdir(output, { recursive: true })-const groups = ["Review fixes", "Buildings", "Parks", "Homes & neighbourhoods", "Winter", "Ruins", "People & cargo", "Building condition"]+const groups = ["Review fixes", "Buildings", "Parks", "Homes & neighbourhoods", "Winter", "Ruins", "People & cargo", "Building condition", "Upgrades & worked faces"]const captureSheet = async () => {const previous = await page.locator("#sheet-link").getAttribute("href")await page.getByRole("button", { name: "Save model sheet", exact: true }).click()diff --git a/src/asset-lab/assets.ts b/src/asset-lab/assets.tsindex 1902432..32023c6 100644--- a/src/asset-lab/assets.ts+++ b/src/asset-lab/assets.ts@@ -138,7 +138,7 @@ for (const type of ["fir", "broadleaf", "poplar"] as const)if (type === "fir" && grown === 1) continueadditional.push(makeTree(type, grown, `${type}-${grown === 1 ? "grown" : grown >= 0.5 ? "young" : "sapling"}`))}-for (const ore of [false, true]) for (const full of [false, true]) additional.push(makeRock(ore, full))+for (const ore of [false, true]) for (const stage of [false, true, "worked"] as const) additional.push(makeRock(ore, stage))for (const ore of [false, true]) for (const [w, h] of [[2, 1], [2, 2], [3, 3]] as const) additional.push(makeRock(ore, true, 0, w, h))for (const stage of [0, 1, 2, 3] as const) additional.push(makeField(stage))additional.push(makeRoadPatch(), makeWater(), ...personCatalogue())diff --git a/src/asset-lab/land.ts b/src/asset-lab/land.tsindex fee6743..d97355e 100644--- a/src/asset-lab/land.ts+++ b/src/asset-lab/land.ts@@ -182,12 +182,16 @@ export function oreShard(d: Drawing, u: number, v: number, radius: number, heigh* once over the cells it spans). Stone is a heap of rounded boulders; ore is* slate rubble with shards standing out of it.*/-export function makeRock(ore: boolean, full: boolean, variant = 0, w = 1, h = 1) {+export function makeRock(ore: boolean, stage: boolean | "worked", variant = 0, w = 1, h = 1) {const name=ore?"Ore":"Stone"const size=w*h>1?`-${w}x${h}`:""- const d=new Drawing(`${ore?"ore":"stone"}-${full?"full":"quarried"}${size}`,`${name} · ${full?"full":"quarried"}${size?` · ${w}×${h}`:""}`,"A clustered deposit with clean shaded facets and seeded silhouettes. Stone is pale rounded boulders; ore is dark slate with rust-red shards.")- d.asset.category="land";d.asset.reference={type:"rock",x:ore?5:0,y:ore?3:0,ore,amount:full?40:10};d.asset.footprint=Math.max(w,h)+ const state=stage==="worked"?"worked":stage?"full":"quarried",full=stage===true+ const d=new Drawing(`${ore?"ore":"stone"}-${state}${size}`,`${name} · ${state==="worked"?"worked face":state}${size?` · ${w}×${h}`:""}`,state==="worked"+ ?"Quarried down to a worked face: low cut benches with chisel marks, squared blocks and spoil. It still gives a little, slowly; the bulldozer clears it."+ :"A clustered deposit with clean shaded facets and seeded silhouettes. Stone is pale rounded boulders; ore is dark slate with rust-red shards.")+ d.asset.category="land";d.asset.reference={type:"rock",x:ore?5:0,y:ore?3:0,ore,amount:state==="worked"?1:full?40:10};d.asset.footprint=Math.max(w,h)const A=w*8*U,B=h*8*U,small=Math.min(w,h),grow=1+(small-1)*0.55+ if(state==="worked"){workedFace(d,ore,variant,A,B,grow);return d.asset}// The big rock in the middle, then smaller ones around it, inside the footprint.const spots:Array<[number,number,number]>=[[0.06,-0.02,1]]const around=2+w*h@@ -208,6 +212,46 @@ export function makeRock(ore: boolean, full: boolean, variant = 0, w = 1, h = 1)return d.asset}+/**+ * A deposit quarried down: a low, rough mound where the boulders stood,+ * with a square-cut bench standing in it, chisel-marked, and a cut block or+ * two set down beside it. Ore keeps its slate and a rust seam along the+ * cut. Nothing stands proud, so it reads apart from a half-quarried rock.+ */+function workedFace(d: Drawing, ore: boolean, variant: number, A: number, B: number, grow: number) {+ const c=ore?oreColors:stoneColors+ const benches=Math.max(1,Math.round((A*B)/(64*U*U)))+ for(let i=0;i<benches;i++){+ const t=i*2.4+variant*0.7,far=benches>1?0.45:0+ const u=Math.cos(t)*(A-5*U)*far+(hash(variant,i)-0.5)*U,v=Math.sin(t)*(B-5*U)*far+(hash(i,variant+4)-0.5)*U+ const a=(3+hash(i+2,variant)*0.6)*U*grow,b=(2.4+hash(variant+1,i)*0.6)*U*grow+ // The rough mound that is left, low to the ground.+ rockOutcrop(d,u,v,a*1.05,2.6*grow,ore,variant+i*5)+ // The bench: cut square, the stone's own colour on its sawn faces.+ const su=u+a*0.15,sv=v-b*0.1,sa=a*0.55,sb=b*0.6,h=4.4*Math.sqrt(grow)+ let start=d.asset.faces.length+ d.box(su,sv,sa,sb,0,h,c.top,c.left,c.right,0.8)+ d.volume(start,0.6)+ for(const k of [-0.55,-0.1,0.35]){+ d.line([[su+sa+0.02,sv+k*sb,h*0.25],[su+sa+0.02,sv+k*sb+0.5*U,h*0.75]],0.6,palette.ink,0.5)+ d.line([[su+k*sa,sv+sb+0.02,h*0.25],[su+k*sa+0.5*U,sv+sb+0.02,h*0.75]],0.6,palette.ink,0.5)+ }+ if(ore){+ d.face([[su+sa+0.015,sv-sb,h*0.45],[su+sa+0.015,sv+sb,h*0.45],[su+sa+0.015,sv+sb,h*0.6],[su+sa+0.015,sv-sb,h*0.6]],RUST,0)+ d.face([[su-sa,sv+sb+0.015,h*0.45],[su+sa,sv+sb+0.015,h*0.45],[su+sa,sv+sb+0.015,h*0.6],[su-sa,sv+sb+0.015,h*0.6]],RUST,0)+ }+ // A cut block or two set down beside the mound.+ for(let k=0;k<2;k++){+ const s=(0.7+hash(k+i,variant+9)*0.3)*U,bu=u+(k?-0.45:0.5)*a,bv=v+(k?1:-1)*(b+s+0.4*U)+ start=d.asset.faces.length+ d.box(bu,bv,s*1.3,s,0,1.7,c.top,c.left,c.right,0.8)+ d.volume(start,0.6)+ }+ }+ // Spoil: small chips of what was cut.+ for(const [fu,fv] of [[-0.6,0.55],[0.6,-0.45],[-0.75,-0.2]] as const)rockOutcrop(d,fu*(A-1.5*U),fv*(B-1.5*U),0.55*U,1,ore,variant+Math.round(fv*10))+}+export function makeField(stage: 0 | 1 | 2 | 3) {const d = new Drawing(`field-${stage}`,diff --git a/src/asset-lab/service-upgrades.ts b/src/asset-lab/service-upgrades.tsindex cc56ffa..2baa5bc 100644--- a/src/asset-lab/service-upgrades.ts+++ b/src/asset-lab/service-upgrades.ts@@ -1,26 +1,98 @@import { U } from "../iso.ts"import { kinds } from "../content.ts"import { makeBuilding } from "./buildings.ts"-import { Drawing, palette, pale, sides, type Side, type Vertex } from "./primitives.ts"+import { Drawing, palette, pale, sides, type InkAsset, type Side, type Vertex } from "./primitives.ts"export type ServiceKind = "market" | "chapel"+const blue = 0x3d6db5+const stone = { top: 0xf0f1eb, left: 0xe1e5dc, right: 0xd3d9cf }+const timber = { top: 0xeee2c8, left: 0xdcc9a8, right: 0xc6b18e }++/**+ * How a tier 2 building is drawn in the town: without its plate (the town+ * draws plates apart), and turned so its street fronts face the roads.+ */+export interface UpgradeOptions {+ plate?: boolean+ /** The sides with a road at the door; the model turns a quarter at a time to face the most of them. */+ doors?: Partial<Record<Side, boolean>>+}+/** Presentation assets only. Service costs, unlocks and upgrade rules belong to the simulation. */-export function serviceBuilding(kind: ServiceKind, tier: 1 | 2) {+export function serviceBuilding(kind: ServiceKind, tier: 1 | 2, options: UpgradeOptions = {}) {if (tier === 1) return makeBuilding(kind)- return kind === "market" ? marketHall() : church()+ return kind === "market" ? marketHall(options) : church(options)}-const blue = 0x3d6db5-const stone = { top: 0xf0f1eb, left: 0xe1e5dc, right: 0xd3d9cf }-const timber = { top: 0xeee2c8, left: 0xdcc9a8, right: 0xc6b18e }+/** Each upgrade's height to its eaves and to its highest point, for markers and surface effects. */+export const upgradeHeights: Readonly<Record<ServiceKind, { readonly eave: number; readonly top: number }>> = {+ market: { eave: 44, top: 62 },+ chapel: { eave: 52, top: 125 }+}++/** The sides each upgrade is drawn with its street fronts on: the market hall's arcades, the church's tower door. */+const fronts: Readonly<Record<ServiceKind, ReadonlyArray<Side>>> = { market: ["right", "left"], chapel: ["left"] }++/** A quarter turn: left (+v) → right (+u) → backLeft (−v) → backRight (−u). */+const turnSide: Readonly<Record<Side, Side>> = { left: "right", right: "backLeft", backLeft: "backRight", backRight: "left" }+const turnSides = (side: Side, quarters: number) => Array.from({ length: quarters }).reduce<Side>((s) => turnSide[s], side)++/** Quarter turns (0–3) that put the most of `fronts` on a road; the drawn way round when none does. */+export const quartersFor = (kind: ServiceKind, doors: Partial<Record<Side, boolean>> | undefined): number => {+ if (!doors) return 0+ let best = 0, most = 0+ for (let q = 0; q < 4; q++) {+ const n = fronts[kind].filter((f) => doors[turnSides(f, q)]).length+ if (n > most) (best = q), (most = n)+ }+ return best+}++const lightAndDark = (c: number): [number, number] => [pale(c, 0.7), pale(c, 0.52)]+/**+ * The shading is baked in: faces looking +v or −u are lit, +u or −v shaded.+ * Each pair here is one material lit and shaded, so a turned face can take+ * the shade of the way it now looks.+ */+const shadePairs: ReadonlyArray<readonly [number, number]> = [+ [palette.left, palette.right],+ [stone.left, stone.right],+ [timber.left, timber.right],+ lightAndDark(0x8a6a45),+ lightAndDark(blue)+]++/** Turns an asset a quarter at a time about its plot's middle, keeping its light from the same side. */+function turned(asset: InkAsset, quarters: number): InkAsset {+ if (quarters === 0) return asset+ const turn = ([u, v, z]: Vertex): Vertex => {+ for (let i = 0; i < quarters; i++) [u, v] = [v, -u]+ return [u, v, z]+ }+ const faces = asset.faces.map((face) => {+ const points = face.points.map(turn)+ const pair = shadePairs.find((p) => p.includes(face.color))+ if (!pair) return { ...face, points }+ // Which way it looked: its axis from its own plane, the side of that axis from its shade.+ const [a, b, c] = face.points as [Vertex, Vertex, Vertex]+ const nu = (b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1])+ const nv = (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2])+ if (Math.abs(nu) < 1e-9 && Math.abs(nv) < 1e-9) return { ...face, points }+ const lit = face.color === pair[0]+ const was: Vertex = Math.abs(nu) > Math.abs(nv) ? [lit ? -1 : 1, 0, 0] : [0, lit ? 1 : -1, 0]+ const [u, v] = turn(was)+ return { ...face, points, color: v > 0.5 || u < -0.5 ? pair[0] : pair[1] }+ })+ return { ...asset, faces, strokes: asset.strokes.map((s) => ({ ...s, points: s.points.map(turn) })) }+}-function base(kind: ServiceKind, id: string, title: string, note: string) {+function base(kind: ServiceKind, id: string, title: string, note: string, options: UpgradeOptions) {const d = new Drawing(id, title, note)d.asset.category = "buildings"d.asset.reference = { type: "building", kind, tier: 2 }d.asset.footprint = kinds[kind].size- d.plate(kinds[kind].size)+ if (options.plate !== false) d.plate(kinds[kind].size)return d}@@ -76,8 +148,8 @@ function churchDoor(d: Drawing, p: Wall) {d.line([p(0, bottom, 0.025), p(0, 22, 0.025)], 0.7, 0x7d6140)}-export function marketHall() {- const d = base("market", "market-hall", "Market hall", "Tier 2 market. A pitched hall above a covered arcade, with the market's striped awnings, blue trim and goods crates. Same 2×2 plot.")+export function marketHall(options: UpgradeOptions = {}) {+ const d = base("market", "market-hall", "Market hall", "Tier 2 market. A pitched hall above a covered arcade, with the market's striped awnings, blue trim and goods crates. Same 2×2 plot.", options)const a = 9 * Ud.box(0, 0, 10 * U, 10 * U, 0, 3, stone.top, stone.left, stone.right)d.box(0, 0, a, a, 3, 40)@@ -138,11 +210,11 @@ export function marketHall() {d.face([p(-2 * U, 47), p(2 * U, 47), p(2 * U, 51), p(-2 * U, 51)], pale(blue, 0.28), 1)for (const s of [-U, 0, U]) d.line([p(s, 48, 0.02), p(s, 50, 0.02)], 0.7, 0xf7f3ea)}- return d.asset+ return turned(d.asset, quartersFor("market", options.doors))}-export function church() {- const d = base("chapel", "church", "Church", "Tier 2 chapel. A slate-blue nave, stone buttresses, arched glass and an open belfry with a bronze bell. Same 2×2 plot.")+export function church(options: UpgradeOptions = {}) {+ const d = base("chapel", "church", "Church", "Tier 2 chapel. A slate-blue nave, stone buttresses, arched glass and an open belfry with a bronze bell. Same 2×2 plot.", options)const a = 7 * U, b = 11 * Ud.box(0, 0, 8 * U, 12 * U, 0, 3, stone.top, stone.left, stone.right)d.box(0, 0, a, b, 3, 48)@@ -196,5 +268,5 @@ export function church() {d.box(sign * 11 * U, 9 * U, 1.5 * U, 3 * U, 0, 2, stone.top, stone.left, stone.right, 0.8)for (const v of [7.5, 10.5]) d.ellipsoid(sign * 11 * U, v * U, 4, 1.5 * U, 1.5 * U, 2.5, 0xccd5ae, 0.7, 0xe8ecd2, 12)}- return d.asset+ return turned(d.asset, quartersFor("chapel", options.doors))}diff --git a/src/content.ts b/src/content.tsindex adad3a5..b271d72 100644--- a/src/content.ts+++ b/src/content.ts@@ -160,6 +160,14 @@ export interface Kind {/** 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`). */export interface Upgrade {readonly title: string@@ -302,7 +310,7 @@ export const kinds: Readonly<Record<KindId, Kind>> = {cost: { coins: 200, materials: { planks: 6, stone: 6 } }, upkeep: 10, workers: 1, crew: "citizens", unlock: { residents: 15, citizens: 0 }, buildable: true,service: { service: "faith", seconds: 8, range: 22 }, appeal: { value: 4, reach: 4, full: 2 },upgrade: {- title: "Church", blurb: "a church with a tower: its priest walks further, more often, and the streets around it are the finest", rank: 3,+ title: "Church", blurb: "a church with a tower: its priest walks further, more often, and the streets around it are the finest", rank: 2,cost: { coins: 700, materials: { planks: 8, stone: 20, tools: 3 } }, upkeep: 18,service: { seconds: 6, range: 30 }, appeal: { value: 6, reach: 5, full: 3 }}diff --git a/src/host.ts b/src/host.tsindex c697f1e..3871649 100644--- a/src/host.ts+++ b/src/host.ts@@ -1735,7 +1735,8 @@ export const createHost = async (const story = el("div", "chronicle")story.innerHTML = s.chronicle.filter((l) => l.tick >= s.fate.began * 3600)- .map((l) => `<p><b>${clockText(Math.round(l.tick / 60))}</b> ${l.text}</p>`)+ // Timed from the start of this term, as its chart is.+ .map((l) => `<p><b>${clockText(Math.round((l.tick - s.fate.began * 3600) / 60))}</b> ${l.text}</p>`).join("")card.append(story)const actions = el("div", "actions")diff --git a/src/model-review/main.ts b/src/model-review/main.tsindex e8b9134..824c4a2 100644--- a/src/model-review/main.ts+++ b/src/model-review/main.ts@@ -11,7 +11,8 @@ const families = {winter: { title: "Winter", ids: ["cottage-winter", "citizen-winter", "townhouse-winter", "granary-winter", "smokehouse-winter", "firewatch-winter", "healer-winter", "hospital-winter", "watchhouse-winter", "builder-winter"] },hazards: { title: "Ruins", ids: ["ruin-burnt-1", "ruin-collapsed-1", "ruin-derelict-1"] },people: { title: "People & cargo", ids: ["service-watchman", "service-firefighter", "service-physician", "service-constable", "service-builder", "goods-smoked", "cart-smoked-4", "barrow-smoked-4"] },- wear: { title: "Building condition", ids: ["granary-worn", "smokehouse-worn", "firewatch-worn", "healer-worn", "hospital-worn", "watchhouse-worn", "builder-worn"] }+ wear: { title: "Building condition", ids: ["granary-worn", "smokehouse-worn", "firewatch-worn", "healer-worn", "hospital-worn", "watchhouse-worn", "builder-worn"] },+ upgrades: { title: "Upgrades & worked faces", ids: ["market", "market-hall", "chapel", "church", "stone-full", "stone-quarried", "stone-worked", "ore-full", "ore-quarried", "ore-worked"] }} as consttype Family = keyof typeof familiesconst root = document.querySelector<HTMLElement>("#review")!diff --git a/src/present.ts b/src/present.tsindex a500f6e..e642a4f 100644--- a/src/present.ts+++ b/src/present.ts@@ -12,7 +12,7 @@ import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "./art.timport { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, RuinView } from "./render3d/views.ts"import type { DoorSet, OverlayCell } from "./render3d/models.ts"import {- amounts, BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,+ 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 Tier} from "./content.ts"import { around, canPlace, cellOf, doors, entrances, isRoad, key, lPath, nearest, reach, useAt, type TileLike } from "./grid.ts"@@ -167,11 +167,11 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: C* them to grow, not on a forester. A quarry or mine has rocks in reach,* worked down to their faces: it is waiting on the next one.*/-const growingNear = (grid: GridValue, tile: TileLike, kind: Kind): boolean => {+const growingNear = (grid: GridValue, tile: TileLike, kind: Kind, rocks: ReadonlyMap<number, { readonly ore: boolean }>): boolean => {const g = kind.gathersif (!g || g.source === "water") return false- const use = g.source === "stone" || g.source === "ore" ? "rock" : g.source- return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === use)+ if (g.source === "stone" || g.source === "ore") return around(tile, g.radius).some((c) => rocks.get(key(c.x, c.y))?.ore === (g.source === "ore"))+ return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === g.source)}const BuildingRead = Game.Query({@@ -379,6 +379,8 @@ export const Interact = Game.System(const rates = resources.policy.get()const approval = resources.mood.get().approvalconst cells = resources.appeal.get().cells+ // The rocks by cell: which are ore, and which are worked down to their faces.+ const rockAt = new Map(queries.rocks.each().map(({ data }) => [key(data.tile.get().x, data.tile.get().y), data.rock.get()]))const tick = resources.time.get().tickconst buildings = queries.buildings.each()const houses = queries.houses.each()@@ -620,6 +622,14 @@ export const Interact = Game.System(preview.plots.push({ ...cell, size: 1, look: "blocked" })const there = cell ? parkAt.get(key(cell.x, cell.y))?.data.park.get() : undefinedif (there) preview.tooltip = there.prop !== "none" ? `remove the ${props[there.prop].title.toLowerCase()}` : `remove the ${grounds[there.ground].title.toLowerCase()}`+ const rock = cell ? rockAt.get(key(cell.x, cell.y)) : undefined+ if (rock && cell) {+ const worked = rock.amount <= 1+ if (worked) preview.plots.push({ ...cell, size: 1, look: "blocked" })+ preview.tooltip = worked+ ? `worked ${rock.ore ? "ore" : "stone"} face · clear it for building: it gives no more`+ : `${rock.ore ? "ore" : "stone"} · ${rock.amount} left · quarry it down to a worked face before it can be cleared`+ }}if (ui.selected !== null) {const row = buildings.find((b) => b.entity.id === ui.selected)@@ -780,7 +790,7 @@ export const Interact = Game.System(})const upkeep = upkeepOf(kind, upgraded)if (upkeep > 0) lines.push({ icon: "upkeep", label: "upkeep", value: `${upkeep} coins a minute` })- const growing = status === "starved" && growingNear(grid, row.data.tile.get(), kind)+ const growing = status === "starved" && growingNear(grid, row.data.tile.get(), kind, rockAt)const problem = row.data.burning.present ? "on fire!" : problemOf(kind, status, growing, { nearby: staff.nearby, crew: kind.crew })return { kind, status, problem, lines }}@@ -936,7 +946,7 @@ export const Interact = Game.System(if (hoveredBuilding) {const { kind, status, problem } = describeBuilding(hoveredBuilding)preview.tooltip = ui.tool === "bulldoze"- ? `${kind.title.toLowerCase()} · ${hoveredBuilding.data.hall.present ? "the town hall stays" : salvageFor(kind.cost, maybe(hoveredBuilding.data.site))}`+ ? `${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}`} else if (hoveredHouse) {const h = hoveredHouse.data.house.get()@@ -985,7 +995,7 @@ export const Interact = Game.System(lines,pausable,paused: pickedBuilding.data.paused.present,- salvage: salvageFor(kind.cost, maybe(pickedBuilding.data.site)),+ salvage: salvageFor(builtCost(kind, upgraded), maybe(pickedBuilding.data.site)),upgraded,upgrade: up && standing && !upgraded? { title: up.title, cost: costText(up.cost), blocked: upgradeBlock(up, resources.fate.get().rank, { ranks }) }diff --git a/src/render3d/models.ts b/src/render3d/models.tsindex d7a5465..f0e0c71 100644--- a/src/render3d/models.ts+++ b/src/render3d/models.ts@@ -9,6 +9,7 @@ import { key, cellOf, DIRS } from "../grid.ts"import type { Preview } from "../ui.ts"import { withAppearance, type Appearance } from "../asset-lab/appearance.ts"import { setts } from "../asset-lab/town-props.ts"+import { serviceBuilding, upgradeHeights, type ServiceKind } from "../asset-lab/service-upgrades.ts"export type DoorSet = Record<Side, boolean>export const noDoors: DoorSet = { right: false, left: false, backRight: false, backLeft: false }@@ -62,10 +63,17 @@ export function constructionAsset(size: number, half: number, height: number, buif (stage.walls > 0) d.box(0, 0, a, a, 0, Math.max(2, Math.round(height * stage.walls)))return d.asset}-export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number, appearance: Appearance = {}) {+/** 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 : kinds[id].roof === "gable" ? 20 : kinds[id].stories * 32+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) {const kind = kinds[id],stage = buildStages(build)if (build < 0.78) return 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)return build >= 1 ? withAppearance(asset, kind.half * U, kind.roof === "gable" ? 20 : kind.stories * 32, appearance) : asset}diff --git a/src/render3d/views.ts b/src/render3d/views.tsindex 2115abf..80678f3 100644--- a/src/render3d/views.ts+++ b/src/render3d/views.ts@@ -19,12 +19,13 @@ import { makeSails, makeFlag } from "../asset-lab/buildings.ts"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, homeAsset, homeKey, doorKey, noDoors, quantizeBuild, plateAsset, treeVariant } from "./models.ts"+import { buildingAsset, buildingHeight, homeAsset, homeKey, doorKey, noDoors, quantizeBuild, plateAsset, treeVariant } from "./models.ts"import type { GameScene, SceneNode } from "./scene.ts"/** Winter's cold light complements the roof snow shader. */@@ -123,47 +124,45 @@ 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- this.body.use(`building/${this.kindId}/${build}/${share}/${doorKey(doors)}/${open}`, () =>- buildingAsset(this.kindId, build, share, doors, open)+ // 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))this.plate.use(`plate/${kind.size}/${build}`, () => plateAsset(kind.size, build))- // An upgraded building (a market hall, a church) stands taller.- const tall = look.upgraded ? 1.35 : 1- this.body.root.scale.set(1 + this.pulse * 0.04, tall * (1 - this.pulse * 0.06), 1 + this.pulse * 0.04)- const base = kind.roof === "gable" ? 20 : kind.stories * 32- const H = base * tall- this.marker.root.position.set(- 0,- (H +- (kind.topper === "chimney" ? 24 : kind.topper === "cupola" ? 25 : kind.topper === "flag" ? 24 : kind.topper === "sails" ? 16 : 0) +- 8) /- Math.cos(Math.PI / 6),- 0- )+ this.body.root.scale.set(1 + this.pulse * 0.04, 1 - this.pulse * 0.06, 1 + this.pulse * 0.04)+ const H = buildingHeight(this.kindId, upgraded)+ const top = upgraded+ ? upgradeHeights[this.kindId as "market" | "chapel"].top+ : H + (kind.topper === "chimney" ? 24 : kind.topper === "cupola" ? 25 : kind.topper === "flag" ? 24 : kind.topper === "sails" ? 16 : 0)+ 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 && !signedconst state = structureState(look,this.stage.frost)this.body.effects = build >= 1 ? state : surfaceState()this.body.effectBounds.set(kind.half * U * 32 * Math.SQRT2,H/Math.cos(Math.PI/6),this.entity%97/97,1)+ if(this.effects&&this.effects.group.userData.upgraded!==upgraded){this.effects.dispose();this.effects=null}if(!this.effects&&build>=1&&(state.burning||state.fireRisk)){- this.effects = new StructureEffects(buildingAsset(this.kindId,1,null,noDoors,0),H)+ this.effects = new StructureEffects(buildingAsset(this.kindId,1,null,upgraded?doors:noDoors,0,{},upgraded),H)+ this.effects.group.userData.upgraded=upgradedthis.group.add(this.effects.group)}this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)this.shade = 0xffffff- this.motion.root.visible = look.build >= 1 && (kind.topper === "flag" || kind.topper === "sails")+ // 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")if (kind.topper === "flag") {this.wave += dt * (look.working ? 6 : 3)this.motion.use("flag/" + this.kindId, () => makeFlag(this.kindId))const a = kind.half * U,pitch = (2 * a) / kind.bays- this.motion.root.position.copy(vertex3([-a + pitch * (kind.bays - 0.5), -a + pitch * 0.5, base + 24]))+ this.motion.root.position.copy(vertex3([-a + pitch * (kind.bays - 0.5), -a + pitch * 0.5, H + 24]))this.motion.root.rotation.y = Math.sin(this.wave) * 0.15this.motion.root.scale.set(1 + Math.sin(this.wave) * 0.12, 1, 1 + Math.sin(this.wave) * 0.12)} else if (kind.topper === "sails") {if (look.working) this.wave += dt * 3.6this.motion.use("mill-sails", makeSails)- this.motion.root.position.copy(vertex3([kind.half * U + 3 * U, 0, base - 6]))+ this.motion.root.position.copy(vertex3([kind.half * U + 3 * U, 0, H - 6]))this.motion.root.rotation.x = this.wave}const smoking=look.working&&kind.topper==="chimney"&&look.build>=1&&!look.burning@@ -287,8 +286,9 @@ export class RockView extends WorldView {this.anchor.x = this.cell.x + w / 2this.anchor.y = this.cell.y + h / 2this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))- const full = amount > ROCK_AMOUNT / 2- this.body.use(`rock/${ore}/${full}/${this.variant}/${w}x${h}`, () => makeRock(ore, full, this.variant, w, h))+ // Quarried down to its worked face (see `FACE_TICKS`), it gives one at a time: drawn as cut benches.+ const stage = amount <= 1 ? "worked" : amount > ROCK_AMOUNT / 2+ this.body.use(`rock/${ore}/${stage}/${this.variant}/${w}x${h}`, () => makeRock(ore, stage, this.variant, w, h))}}export class FieldView extends WorldView {diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex 589a0e1..223c495 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, goodIds, RESERVE_MAX, TAX_STEPS, ticks, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"+import { amounts, builtCost, goodIds, RESERVE_MAX, TAX_STEPS, ticks, 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, 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 } 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"@@ -44,8 +44,11 @@ export const ApplyEdits = Game.System(parks: Game.Query({ selection: { park: Game.Query.write(Park) } }),halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } }),/** Whatever was built at a cost, standing or a site: what pulling it down gives back. */- built: Game.Query({ selection: { building: Game.Query.optional(Building), house: Game.Query.optional(House), site: Game.Query.optional(Site), paused: Game.Query.optional(Paused) } }),+ built: Game.Query({+ selection: { building: Game.Query.optional(Building), house: Game.Query.optional(House), site: Game.Query.optional(Site), paused: Game.Query.optional(Paused), upgraded: Game.Query.optional(Upgraded) }+ }),stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] }),+ rocks: Game.Query({ selection: { rock: Game.Query.read(Rock) } }),upgradable: Game.Query({selection: {building: Game.Query.read(Building),@@ -281,7 +284,15 @@ export const ApplyEdits = Game.System(if (!inside(edit.cell.x, edit.cell.y)) breakconst use = useAt(grid.value(), edit.cell.x, edit.cell.y)const owner = entities.get(ownerAt(grid.value(), edit.cell.x, edit.cell.y))- if (owner === undefined || use === "rock" || use === "water") break+ if (owner === undefined || use === "water") break+ // A rock goes only once it is quarried down to a worked face, and gives nothing more after.+ if (use === "rock") {+ const rock = queries.rocks.get(owner)+ if (!rock.ok || rock.value.data.rock.get().amount > 1) {+ ui.toast("Quarry it down first: only a worked face can be cleared")+ break+ }+ }if (halls.has(owner)) {ui.toast("The town hall stays")break@@ -296,7 +307,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 ? kinds[b.kind].cost : home.cost, maybe(built.value.data.site)?.owed ?? null, rules)+ const s = salvageOf(b ? builtCost(kinds[b.kind], built.value.data.upgraded.present) : 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@@ -373,8 +384,8 @@ export const ApplyEdits = Game.System(const winters = [...charter.winters]while (winters.length < term * rules.yearsPerTerm) winters.push(...rollWinters(() => almanac.next(), rules, false))resources.charter.set({ ...charter, winters: winters.slice(0, term * rules.yearsPerTerm) })- // The crown starts the term afresh: an open request lapses, unfined.- resources.crown.update((c) => ({ ...c, open: false, next: began + crownGap(charter, rules) }))+ // The crown starts the term afresh: an open request lapses, unfined, and its tally of requests met and missed begins again.+ resources.crown.update((c) => ({ ...c, open: false, next: began + crownGap(charter, rules), met: 0, missed: 0, streak: 0 }))resources.fate.set({ ...f, state: "playing", reason: "", term, began, debtSince: -1, revoltSince: -1, goalSince: -1, score: 0 })// A long reign keeps its history in less detail the further back it is.const samples = resources.history.get().samplesdiff --git a/test/endless.test.ts b/test/endless.test.tsindex fc34ffa..0209aff 100644--- a/test/endless.test.ts+++ b/test/endless.test.ts@@ -132,3 +132,81 @@ test("once a term runs out, the next one carries on the same town", () => {assert(s.resources["Town/Crown"].next > end)assert(s.resources["Town/Chronicle"].lines.some((l: { text: string }) => l.text.startsWith("Term 2:")))})++test("a long reign: five terms follow one another, each judged on its own, and the save stays in bounds", () => {+ const t = headless(charter)+ t.run(16)+ const term = charter.term * 3600+ const sample = t.snapshot().resources["Town/History"].samples.at(-1)+ assert(sample, "a sample of the town's history")+ for (let n = 1; n <= 5; n++) {+ // The term's history, as a long term would leave it, and the crown's tally from it; then its last seconds.+ t.change((s) => {+ const f = s.resources["Town/Fate"]+ const samples = s.resources["Town/History"].samples+ for (let i = 1; i <= 400; i++) samples.push({ ...sample, tick: f.began + Math.round((i * term) / 401) })+ s.resources["Town/Crown"] = { ...s.resources["Town/Crown"], met: 3, missed: 2, streak: 2 }+ s.resources["Town/Time"].tick = s.resources["Town/Charter"].founded + f.began + term - 120+ s.resources["Town/Treasury"].coins = 5000+ })+ t.run(3)+ const over = t.snapshot().resources["Town/Fate"]+ assert.equal(over.state, "over", `term ${n} runs out on time`)+ assert.equal(over.term, n)+ assert.equal(over.began, (n - 1) * term)+ assert.match(over.reason, new RegExp(`^Term ${n} is over`))+ t.edit({ type: "nextTerm" })+ t.run(1)+ const s = t.snapshot()+ // The crown's tally starts again, so a term is scored on its own requests and no mayor starts one near dismissal.+ assert.deepEqual([s.resources["Town/Crown"].met, s.resources["Town/Crown"].missed, s.resources["Town/Crown"].streak], [0, 0, 0])+ assert.equal(s.resources["Town/Fate"].term, n + 1)+ }+ const s = t.snapshot()+ const samples: ReadonlyArray<{ tick: number }> = s.resources["Town/History"].samples+ // Older history thins (past 1200 samples), the term just played stays whole, and the samples stay in order.+ assert(samples.length < 5 * 400, `history thinned: ${samples.length} samples`)+ assert.equal(samples.filter((p) => p.tick >= 4 * term).length >= 400, true)+ assert(samples.every((p, i) => i === 0 || p.tick >= samples[i - 1]!.tick))+ assert(s.resources["Town/Chronicle"].lines.length <= 200)+ assert.equal(s.resources["Town/Charter"].winters.length, 6 * YEARS_PER_TERM)+ const size = JSON.stringify(s).length+ assert(size < 600_000, `save size ${size}`)+})++test("the bulldozer clears a worked face, but not a rock still standing", () => {+ const toasts: Array<string> = []+ const t = headless(charter, { toast: (m) => toasts.push(m) })+ t.run(1)+ const rocks = t.snapshot().entities.filter((e) => e.components["Town/Rock"])+ const [worked, standing] = [rocks[0]!, rocks[1]!]+ t.change((s) => {+ s.entities.find((e) => e.id === worked.id)!.components["Town/Rock"].amount = 0+ s.entities.find((e) => e.id === standing.id)!.components["Town/Rock"].amount = 12+ })+ t.edit({ type: "remove", cell: worked.components["Town/Tile"] }, { type: "remove", cell: standing.components["Town/Tile"] })+ t.run(1)+ const left = new Set(t.snapshot().entities.map((e) => e.id))+ assert.equal(left.has(worked.id), false)+ assert.equal(left.has(standing.id), true)+ assert(toasts.some((m) => m.startsWith("Quarry it down first")), toasts.join(" | "))+})++test("pulling down a market hall gives back part of the upgrade too", () => {+ const t = headless(charter)+ t.run(1)+ let cell = { x: 0, y: 0 }+ t.change((s) => {+ cell = market(s)+ s.resources["Town/Fate"].rank = 2+ })+ t.edit({ type: "upgrade", cell })+ t.run(1)+ const stone = stockOf(t.snapshot(), "stone")+ t.edit({ type: "remove", cell })+ t.run(1)+ const back = stockOf(t.snapshot(), "stone") - stone+ const base = kinds.market.cost.materials.stone!, up = kinds.market.upgrade!.cost.materials.stone!+ assert(back > Math.floor(base / 2), `${back} stone back, more than the market's own share`)+ assert(back <= base + up)+})diff --git a/test/ink-assets.test.ts b/test/ink-assets.test.tsindex e688285..5c7c867 100644--- a/test/ink-assets.test.ts+++ b/test/ink-assets.test.ts@@ -5,6 +5,7 @@ import { kindIds, goodIds, kinds } from "../src/content.ts"import { testMap } from "../src/map-lab/map.ts"import { U } from "../src/iso.ts"import { makeRock } from "../src/asset-lab/land.ts"+import { church, marketHall, quartersFor } from "../src/asset-lab/service-upgrades.ts"test("the portable catalogue covers all world object families", () => {assert.equal(assetById.size, inkAssets.length, "Asset IDs must be unique")@@ -22,8 +23,8 @@ test("the portable catalogue covers all world object families", () => {assert.deepEqual([...hats].sort(), ["bonnet", "brim", "cap", "hood", "none", "top"])for (const tier of [1, 2]) assert.equal(inkAssets.filter((a) => a.reference?.type === "house" && a.reference.tier === tier && !a.appearance).length, 4)assert.equal(inkAssets.filter((a) => a.reference?.type === "tree").length, 9)- // Stone and ore, full and quarried, one cell; and full outcrops over 2×1, 2×2, and 3×3 cells.- assert.equal(inkAssets.filter((a) => a.reference?.type === "rock").length, 10)+ // Stone and ore, full, quarried, and worked down to a face, one cell; and full outcrops over 2×1, 2×2, and 3×3 cells.+ assert.equal(inkAssets.filter((a) => a.reference?.type === "rock").length, 12)assert.equal(inkAssets.filter((a) => a.reference?.type === "field").length, 4)})@@ -67,9 +68,32 @@ test("the review map includes every catalogue model at least once", () => {})test("buildings, homes and resource deposits stay inside their plates", () => {- const models = [...inkAssets.filter(a=>a.reference?.type==="building"||a.reference?.type==="house"),...Array.from({length:6},(_,i)=>[makeRock(false,true,i),makeRock(true,true,i)]).flat()]+ const models = [...inkAssets.filter(a=>a.reference?.type==="building"||a.reference?.type==="house"),...Array.from({length:6},(_,i)=>[makeRock(false,true,i),makeRock(true,true,i),makeRock(false,"worked",i),makeRock(true,"worked",i),makeRock(false,"worked",i,3,3)]).flat()]for(const a of models){const half=(a.footprint!*8-1)*Ufor(const p of [...a.faces.flatMap(f=>f.points),...a.strokes.flatMap(s=>s.points)])assert.ok(Math.abs(p[0])<=half+0.0001&&Math.abs(p[1])<=half+0.0001,`${a.id}: geometry outside the ${a.footprint}-cell plate`)}})++test("an upgraded market or church turns to face its road, keeping its plot and its light", () => {+ for (const side of ["right", "left", "backRight", "backLeft"] as const) {+ const doors = { [side]: true }+ const q = quartersFor("chapel", doors)+ assert.ok(q >= 0 && q < 4)+ for (const asset of [church({ plate: false, doors }), marketHall({ plate: false, doors })]) {+ const edge = (kinds.market.size * 8 - 1) * U+ assert.ok(asset.faces.every((f) => f.points.every(([u, v]) => Math.abs(u) <= edge + 1e-9 && Math.abs(v) <= edge + 1e-9)), `${asset.id} facing ${side}`)+ assert.ok(!asset.faces.some((f) => f.color === 0xf5f6f2), `${asset.id}: no plate in the town`)+ }+ }+ // The church's tower door is on its +v side as drawn: turned to the road on each side.+ const towerAt = (doors: Record<string, boolean>) => {+ const tall = church({ plate: false, doors }).faces.flatMap((f) => f.points).filter((p) => p[2] > 110)+ const [u, v] = [tall.reduce((n, p) => n + p[0], 0) / tall.length, tall.reduce((n, p) => n + p[1], 0) / tall.length]+ return Math.abs(u) > Math.abs(v) ? (u > 0 ? "right" : "backRight") : v > 0 ? "left" : "backLeft"+ }+ for (const side of ["right", "left", "backRight", "backLeft"]) assert.equal(towerAt({ [side]: true }), side)+ // Lit faces stay lit: as many of the church's faces carry the lit wall colour whichever way it turns.+ const lit = (doors: Record<string, boolean>) => church({ plate: false, doors }).faces.filter((f) => f.color === 0xe9ebe5).length+ assert.equal(lit({ right: true }), lit({ left: true }))+})