Skip to content

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

Migrate Inkline to Ritmo clocks and preserve existing saves

SandroMaglione8cd8d230261f
diff --git a/.gitignore b/.gitignore
index 28b7584..7492e39 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
node_modules
+.repos/
dist
.alchemy
.env
diff --git a/PLAYTEST.md b/PLAYTEST.md
index 9a69614..3ffbcb4 100644
--- a/PLAYTEST.md
+++ b/PLAYTEST.md
@@ -6,8 +6,12 @@ without a browser to see exactly what happened, step by step.
## 1. Start the dev build
+This branch pins the Ritmo source commit while the new package names await
+publication. Prepare it before installing the game:
+
```sh
-pnpm install
+pnpm engine:prepare
+pnpm install --frozen-lockfile
pnpm dev
```
@@ -19,7 +23,7 @@ Open the address it prints (usually http://localhost:5173). Replays work in
Any of these saves the last minute of play:
- **The button.** Press `\` (backslash) or the "◉ monitor" button in the
- corner to open the bevy-ts monitor, then **Save replay**. Do it right after
+ corner to open the Ritmo monitor, then **Save replay**. Do it right after
you see the problem: the replay holds the last 60 seconds before the press.
- **By itself, when a step fails.** If the simulation fails, a replay is
saved without you doing anything.
diff --git a/package.json b/package.json
index 88ee0ce..c2f02f9 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
"balance:worth": "node scripts/worth.ts",
"balance:furniture": "node scripts/furniture.ts",
"balance:model:check": "node --test test/balance-model.test.ts",
- "lint:game": "bevy-ts-devtools lint src/sim/headless.ts",
+ "lint:game": "ritmo-devtools lint src/sim/headless.ts",
"replay": "node scripts/replay.ts",
"check": "pnpm lint && pnpm lint:game && node scripts/check.ts",
"check:browser": "node scripts/check-browser.ts",
@@ -28,25 +28,28 @@
"look:ui": "node scripts/look-ui.ts",
"test": "node --test \"test/*.test.ts\"",
"lint": "oxlint --ignore-pattern 'tools/lint/fixtures/**' src test scripts tools",
- "release": "pnpm --dir deploy release"
+ "release": "pnpm --dir deploy release",
+ "engine:prepare": "node scripts/use-ritmo.ts"
},
"dependencies": {
- "@typeonce/bevy-ts": "^0.5.0",
- "@typeonce/bevy-ts-browser": "^0.5.0",
- "@typeonce/bevy-ts-math": "^0.5.0",
- "@typeonce/bevy-ts-pixi": "^0.5.0",
- "@typeonce/bevy-ts-render": "^0.5.0",
+ "@typeonce/ritmo": "link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/core",
+ "@typeonce/ritmo-browser": "link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/browser",
+ "@typeonce/ritmo-math": "link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/math",
+ "@typeonce/ritmo-pixi": "link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/pixi",
+ "@typeonce/ritmo-render": "link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/render",
"effect": "4.0.3",
"pixi.js": "^8.22.0",
"three": "^0.186.1"
},
"devDependencies": {
- "@typeonce/bevy-ts-devtools": "^0.5.0",
+ "@typeonce/ritmo-devtools": "link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/devtools",
"@types/node": "25.5.0",
"@types/three": "^0.186.0",
"oxlint": "1.87.0",
"playwright": "^1.64.0",
"typescript": "7.0.2",
"vite": "8.3.1"
- }
+ },
+ "ritmoRelease": "0.7.0",
+ "ritmoSource": "1ec469fd865ae82d2f53a07f5f1662dd1363fe84"
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1c62ebe..8439f62 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,21 +8,21 @@ importers:
.:
dependencies:
- '@typeonce/bevy-ts':
- specifier: ^0.5.0
- version: 0.5.0([email protected])
- '@typeonce/bevy-ts-browser':
- specifier: ^0.5.0
- version: 0.5.0([email protected])
- '@typeonce/bevy-ts-math':
- specifier: ^0.5.0
- version: 0.5.0([email protected])
- '@typeonce/bevy-ts-pixi':
- specifier: ^0.5.0
- version: 0.5.0([email protected])
- '@typeonce/bevy-ts-render':
- specifier: ^0.5.0
- version: 0.5.0([email protected])
+ '@typeonce/ritmo':
+ specifier: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/core
+ version: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/core
+ '@typeonce/ritmo-browser':
+ specifier: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/browser
+ version: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/browser
+ '@typeonce/ritmo-math':
+ specifier: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/math
+ version: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/math
+ '@typeonce/ritmo-pixi':
+ specifier: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/pixi
+ version: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/pixi
+ '@typeonce/ritmo-render':
+ specifier: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/render
+ version: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/render
effect:
specifier: 4.0.3
version: 4.0.3
@@ -33,9 +33,9 @@ importers:
specifier: ^0.186.1
version: 0.186.1
devDependencies:
- '@typeonce/bevy-ts-devtools':
- specifier: ^0.5.0
- version: 0.5.0([email protected])
+ '@typeonce/ritmo-devtools':
+ specifier: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/devtools
+ version: link:.repos/ritmo-preview/1ec469fd865ae82d2f53a07f5f1662dd1363fe84/packages/devtools
'@types/node':
specifier: 25.5.0
version: 25.5.0
@@ -276,35 +276,6 @@ packages:
'@tweenjs/[email protected]':
resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==}
- '@typeonce/[email protected]':
- resolution: {integrity: sha512-69IcRugcpq0bfd809RtmuZbJ/11zrcTTJyJ0o5kDDTQWY7RtqNUm1layTTbBqnJYl8rkMXP0Qzzu2Pcypz/2pA==}
- engines: {node: '>=20'}
-
- '@typeonce/[email protected]':
- resolution: {integrity: sha512-9N9pTjitHmkQnWy7yYcyr2WD48+yjJ994ZA3ZQK44TtZJ6lRQ5SH+7Dfe/sb5EurSBzktGYOQAh7coJAx6mh7A==}
- engines: {node: '>=20'}
-
- '@typeonce/[email protected]':
- resolution: {integrity: sha512-uxeRQ8Yhhrl98KdcUYBNeVTzppOnyVlzXinOlEogkHvV3Gal4ctBYVpP36LY/+3oENK3FMQXr5ESJN+cMKj2fQ==}
- engines: {node: '>=20'}
-
- '@typeonce/[email protected]':
- resolution: {integrity: sha512-UVHTm+C0efKLMt0JbMI0MN5lSfLLvnmbAX/3tUxqWmPRQp1rK9cz2PHGi35OL7Lunug3gnX46+WmkLHPxYo57w==}
- engines: {node: '>=20'}
-
- '@typeonce/[email protected]':
- resolution: {integrity: sha512-N83MLOluj6DhWPS6ochmrkFk0KODqngYE1VS3UqFnQ+6KnjPxHlwQCGqvQAm5M4m8rgFabLLFalqW5MpywmGtA==}
- engines: {node: '>=20'}
-
- '@typeonce/[email protected]':
- resolution: {integrity: sha512-YUY0KPYWGLJI5p/dQyTtKQ9HxxmSyFzH2Id5ke4gPZ53+ii3Jv2Ua0C4Y+62YzS2RBQvOmN46woZgF6VSvmUfQ==}
- engines: {node: '>=20'}
- peerDependencies:
- typescript: '>=5.9'
- peerDependenciesMeta:
- typescript:
- optional: true
-
resolution: {integrity: sha512-k/9fOUGO39yd2sCjrbAJvGDEQvRwRnQIZlBz43roGwUZo5SHAmyVvSFyaVVZkicRVCaDXPKlbxrUcBuJoSWunQ==}
@@ -789,40 +760,6 @@ snapshots:
'@tweenjs/[email protected]': {}
- dependencies:
- '@typeonce/bevy-ts': 0.5.0([email protected])
- transitivePeerDependencies:
- - typescript
-
- dependencies:
- '@typeonce/bevy-ts': 0.5.0([email protected])
- transitivePeerDependencies:
- - typescript
-
- dependencies:
- '@typeonce/bevy-ts': 0.5.0([email protected])
- transitivePeerDependencies:
- - typescript
-
- dependencies:
- '@typeonce/bevy-ts-render': 0.5.0([email protected])
- transitivePeerDependencies:
- - typescript
-
- dependencies:
- '@typeonce/bevy-ts': 0.5.0([email protected])
- transitivePeerDependencies:
- - typescript
-
- optionalDependencies:
- typescript: 7.0.2
-
'@types/[email protected]': {}
diff --git a/scripts/balance.ts b/scripts/balance.ts
index f7f5503..93da3c9 100644
--- a/scripts/balance.ts
+++ b/scripts/balance.ts
@@ -206,7 +206,7 @@ const read = (snapshot: Snapshot): World => {
crown: r["Town/Crown"],
fate: r["Town/Fate"],
charter: r["Town/Charter"],
- tick: r["Town/Time"].tick
+ tick: r["Town/Time"].step
}
}
@@ -545,7 +545,7 @@ const decide = (w: World): ReadonlyArray<Edit> => {
const civicShort = w.coins > 600 && count(w, "mill") > 0 && count(w, "weaver") > 0 && count(w, "chapel") > 0 && w.census.citizens! < Math.max(content.sizes[w.charter.size].goal.residents, residents(w)) * content.fate.citizens
// Winter: the fields lie fallow, so flour (which keeps) is laid in for the bakeries before it, and fish bought while it lasts.
const season = seasonAt(w.tick - w.charter.founded, w.charter, rules)
- const bracing = w.coins > 800 && count(w, "bakery") > 0 && (season.winter || (season.coming !== null && season.left < content.ticks(180)))
+ const bracing = w.coins > 800 && count(w, "bakery") > 0 && (season.winter || (season.coming !== null && season.left < content.stepsOf(180)))
const wintry = season.winter && w.coins > 800 && fed < 0.8 && w.stock.fish < 20
const shortages: ReadonlyArray<readonly [GoodId, number, number]> = [["flour", bracing ? 15 : -1, 40], ["bread", civicShort ? 8 : -1, 20], ["cloth", civicShort ? 4 : -1, 12], ["planks", Math.max(6, wanted(w, "planks")), Math.max(14, wanted(w, "planks") + 8)], ["stone", Math.max(4, wanted(w, "stone")), Math.max(12, wanted(w, "stone") + 6)], ["tools", 3, 6], ["fish", (fed < 0.5 && w.stock.fish < 10) || (closing && fed < 0.7 && w.stock.fish < 20) || wintry ? 1000 : -1, 24]]
for (const [g, low, enough] of shortages) {
diff --git a/scripts/check-browser.ts b/scripts/check-browser.ts
index 7da0d40..beb062b 100644
--- a/scripts/check-browser.ts
+++ b/scripts/check-browser.ts
@@ -149,11 +149,11 @@ try {
await page.getByRole("button",{name:"4×",exact:true}).click()
const before=await snapshot()
const positions=await page.evaluate(()=>[...window.town.view.nodes].filter(n=>n.constructor.name==="WalkerView").map(n=>n.group.position.toArray()))
- await page.waitForFunction(t=>window.town.runtime.snapshot().resources["Town/Time"].tick>t+30,before.resources["Town/Time"].tick)
+ await page.waitForFunction(t=>window.town.runtime.snapshot().resources["Town/Time"].step>t+30,before.resources["Town/Time"].step)
await page.locator(".toolbar .pause").click()
const paused=await snapshot(),pf=await page.evaluate(()=>window.town.view.stats().frames)
await page.waitForFunction(f=>window.town.view.stats().frames>f+10,pf)
- assert.equal((await snapshot()).resources["Town/Time"].tick,paused.resources["Town/Time"].tick)
+ assert.equal((await snapshot()).resources["Town/Time"].step,paused.resources["Town/Time"].step)
assert.notDeepEqual(await page.evaluate(()=>[...window.town.view.nodes].filter(n=>n.constructor.name==="WalkerView").map(n=>n.group.position.toArray())),positions)
facts.speedAndPause=true
facts.liveWalkerMovement=true
@@ -185,7 +185,7 @@ try {
await page.setViewportSize({width:1440,height:1000})
// A saved term that has ended still opens the existing reckoning UI.
const ended=structuredClone(grown)
- ended.world.resources["Town/Fate"]={...ended.world.resources["Town/Fate"],state:"over",reason:"The term has ended.",at:ended.world.resources["Town/Time"].tick}
+ ended.world.resources["Town/Fate"]={...ended.world.resources["Town/Fate"],state:"over",reason:"The term has ended.",at:ended.world.resources["Town/Time"].step}
await page.evaluate(save=>localStorage.setItem("inkline-town/save/manual",JSON.stringify({...save,savedAt:Date.now()})),ended)
await page.getByRole("button",{name:"load",exact:true}).click()
await page.getByRole("button",{name:"Load without saving",exact:true}).click()
diff --git a/scripts/check.ts b/scripts/check.ts
index ae2a606..113a777 100644
--- a/scripts/check.ts
+++ b/scripts/check.ts
@@ -25,7 +25,7 @@
* - citizens will not take settlers' work, and settlers stand in for citizens as apprentices;
* - and homes with every need met become citizens on a street with a park behind it, not packed beside industry.
*/
-import { amounts, CONDITION_MAX, goodIds, kinds, RISK_MAX, ticks, type CharterValue, type GroundId, type KindId, type PropId } from "../src/content.ts"
+import { amounts, CONDITION_MAX, goodIds, kinds, RISK_MAX, stepsOf, type CharterValue, type GroundId, type KindId, type PropId } from "../src/content.ts"
import { canPlace, DIRS, entrances, GridBuilder, isRoad, key, type Use } from "../src/grid.ts"
import { inside } from "../src/iso.ts"
import { parkValue, ringOf, type ParkCell } from "../src/appeal.ts"
@@ -272,7 +272,7 @@ const standing = (s: Snapshot, kind: KindId, x: number, y: number, stock: Partia
}
if (k.recipe) {
const r = k.recipe
- c["Town/Recipe"] = { input: r.input, inputs: r.inputs, output: r.output, batch: r.batch, period: ticks(r.seconds), progress: 0, made: 0 }
+ c["Town/Recipe"] = { input: r.input, inputs: r.inputs, output: r.output, batch: r.batch, period: stepsOf(r.seconds), progress: 0, made: 0 }
}
if (k.gathers) c["Town/Gatherer"] = { ...k.gathers }
const tools = k.wear ? ["tools"] : []
@@ -282,7 +282,7 @@ const standing = (s: Snapshot, kind: KindId, x: number, y: number, stock: Partia
if (all || k.keeps) c["Town/Storage"] = {}
} else if (k.recipe) c["Town/Inventory"] = { stock: amounts(stock), accepts: [k.recipe.output, ...tools], cap: 8 }
if (k.carriers) c["Town/Carriers"] = { count: k.carriers }
- if (k.service) c["Town/Service"] = { service: k.service.service, interval: ticks(k.service.seconds), cooldown: 0, range: k.service.range }
+ if (k.service) c["Town/Service"] = { service: k.service.service, interval: stepsOf(k.service.seconds), cooldown: 0, range: k.service.range }
c["Town/Risk"] = { fire: 0, health: 0, order: 0, thefts: 0 }
c["Town/Condition"] = { value: CONDITION_MAX }
const id = s.nextEntity++
diff --git a/scripts/furniture.ts b/scripts/furniture.ts
index da8a451..cd6819d 100644
--- a/scripts/furniture.ts
+++ b/scripts/furniture.ts
@@ -64,7 +64,7 @@ const run = (homes: number, carpenters: number) => {
// Across the street: a market, then the carpenters.
t.edit({ type: "building", kind: "market", cell: { x: hall.x + 4, y: hall.y - 1 }, open: false })
for (let i = 0; i < carpenters; i++) t.edit({ type: "building", kind: "carpenter", cell: { x: hall.x + 6 + 2 * i, y: hall.y - 1 }, open: false })
- const started = t.snapshot().resources["Town/Time"].tick
+ const started = t.snapshot().resources["Town/Time"].step
const samples: Array<Record<string, number | string> & { townhouses: number; made: number }> = []
let firstAll = -1
for (let m = 1; m <= minutes; m++) {
@@ -92,7 +92,7 @@ const run = (homes: number, carpenters: number) => {
samples.push(sample)
if (firstAll < 0 && townhouses === homes) firstAll = m
}
- const ticks = t.snapshot().resources["Town/Time"].tick - started
+ const ticks = t.snapshot().resources["Town/Time"].step - started
const last = samples.at(-1)!
const tail = samples.slice(Math.floor(samples.length / 2))
const held = tail.reduce((n, x) => n + x.townhouses, 0) / tail.length
diff --git a/scripts/look-ui.ts b/scripts/look-ui.ts
index f6d265e..26751de 100644
--- a/scripts/look-ui.ts
+++ b/scripts/look-ui.ts
@@ -71,7 +71,7 @@ for (const [name, width, height, phone] of [["desktop", 1440, 1000, false], ["ph
const f: Tile = fishery.components["Town/Tile"]
await page.evaluate((f) => {
const { runtime } = (window as any).town
- const s = runtime.snapshot(), tick = s.resources["Town/Time"].tick
+ const s = runtime.snapshot(), tick = s.resources["Town/Time"].step
for (const e of s.entities) {
const t = e.components["Town/Tile"], w = e.components["Town/Water"]
if (w && Math.abs(t.x - f.x) <= 3 && Math.abs(t.y - f.y) <= 3) e.components["Town/Water"] = { fished: tick }
diff --git a/scripts/replay.ts b/scripts/replay.ts
index 8888d42..9361758 100644
--- a/scripts/replay.ts
+++ b/scripts/replay.ts
@@ -11,7 +11,7 @@
*/
import { readFileSync, writeFileSync } from "node:fs"
-import { Replay } from "@typeonce/bevy-ts-devtools"
+import { Replay } from "@typeonce/ritmo-devtools"
import { replayTarget } from "../src/sim/headless.ts"
diff --git a/scripts/use-ritmo.ts b/scripts/use-ritmo.ts
new file mode 100644
index 0000000..95a0b4e
--- /dev/null
+++ b/scripts/use-ritmo.ts
@@ -0,0 +1,68 @@
+/**
+ * Points Ritmo packages at an exact source commit or their published npm
+ * release, for builds without the sibling repository (CI and previews):
+ *
+ * node scripts/use-ritmo.ts && pnpm install --no-frozen-lockfile
+ *
+ * `ritmoSource` pins the exact commit used by CI and acceptance builds.
+ * The helper fetches and builds it under `.repos/ritmo-preview/`, without
+ * needing a sibling checkout. Once `ritmoRelease` is published on npm,
+ * remove the source pin and run this helper plus install to switch to it.
+ * It rewrites package.json; installation updates the lockfile.
+ */
+import { execFileSync } from "node:child_process"
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
+import { fileURLToPath } from "node:url"
+
+const file = new URL("../package.json", import.meta.url)
+const pkg = JSON.parse(readFileSync(file, "utf8")) as {
+ ritmoRelease?: string
+ /** Unpublished engine changes, pinned for CI and preview acceptance builds. */
+ ritmoSource?: string
+ dependencies?: Record<string, string>
+ devDependencies?: Record<string, string>
+}
+
+const version = pkg.ritmoRelease
+if (version === undefined) throw new Error("package.json has no ritmoRelease")
+
+// A companion PR can test an unpublished engine commit without changing the
+// sibling checkout. Remove this pin once that commit's release is published.
+const source = pkg.ritmoSource
+let sourcePath: string | undefined
+if (source !== undefined) {
+ if (!/^[a-f0-9]{40}$/.test(source)) throw new Error("ritmoSource must be a full commit SHA")
+ sourcePath = `.repos/ritmo-preview/${source}`
+ const checkout = fileURLToPath(new URL(`../${sourcePath}/`, import.meta.url))
+ const run = (command: string, args: Array<string>) => execFileSync(command, args, { cwd: checkout, stdio: "inherit" })
+ if (!existsSync(`${checkout}.git`)) {
+ mkdirSync(checkout, { recursive: true })
+ run("git", ["init"])
+ run("git", ["remote", "add", "origin", "https://github.com/typeonce-dev/ritmo.git"])
+ }
+ run("git", ["fetch", "--depth=1", "origin", source])
+ run("git", ["checkout", "--detach", source])
+ const actual = execFileSync("git", ["rev-parse", "HEAD"], { cwd: checkout, encoding: "utf8" }).trim()
+ if (actual !== source) throw new Error(`Ritmo checkout mismatch: ${actual}`)
+ run("pnpm", ["install", "--frozen-lockfile"])
+ run("pnpm", ["build"])
+}
+
+const linked: Array<string> = []
+for (const deps of [pkg.dependencies, pkg.devDependencies]) {
+ if (deps === undefined) continue
+ for (const [name, spec] of Object.entries(deps)) {
+ if (name.startsWith("@typeonce/ritmo") && spec.startsWith("link:")) {
+ if (sourcePath === undefined) deps[name] = version
+ else {
+ const packageDir = /\/packages\/([^/]+)$/.exec(spec)?.[1]
+ if (packageDir === undefined) throw new Error(`Unrecognized Ritmo link: ${spec}`)
+ deps[name] = `link:${sourcePath}/packages/${packageDir}`
+ }
+ linked.push(name)
+ }
+ }
+}
+
+writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`)
+console.log(linked.length === 0 ? "No linked Ritmo packages" : `Ritmo ${source ?? version} from ${source === undefined ? "npm" : "pinned source"}: ${linked.join(", ")}`)
diff --git a/src/archetypes.ts b/src/archetypes.ts
index a772463..f592cc3 100644
--- a/src/archetypes.ts
+++ b/src/archetypes.ts
@@ -9,7 +9,7 @@ import { shippedRules, type Rules } from "./rules/config.ts"
import { amounts, goodIds, total, type GroundId, type Kind } from "./content.ts"
import type { Point } from "./iso.ts"
import { Building, Carriers, Condition, Field, Game, Gatherer, House, Inventory, Park, Planter, Recipe, Rising, Risk, Road, Rock, Ruin, Service, Site, Staff, Status, Storage, Tile, Tree, Water } from "./schema.ts"
-import { ticks } from "./content.ts"
+import { stepsOf } from "./content.ts"
const site = (cost: Kind["cost"]) => {
const owed = amounts(cost.materials)
@@ -47,12 +47,12 @@ export const rolesOf = (kind: Kind, rules: Rules = shippedRules) => {
const roles = []
if (kind.recipe) {
const r = kind.recipe
- roles.push(Game.Command.entry(Recipe, { input: r.input, inputs: r.inputs, output: r.output, batch: r.batch, period: ticks(r.seconds), progress: 0, made: 0 }))
+ roles.push(Game.Command.entry(Recipe, { input: r.input, inputs: r.inputs, output: r.output, batch: r.batch, period: stepsOf(r.seconds), progress: 0, made: 0 }))
}
if (kind.gathers) roles.push(Game.Command.entry(Gatherer, { source: kind.gathers.source, radius: kind.gathers.radius }))
if (kind.plants) {
const p = kind.plants
- roles.push(Game.Command.entry(Planter, { what: p.what, radius: p.radius, interval: ticks(p.seconds), cooldown: 0, max: p.max }))
+ roles.push(Game.Command.entry(Planter, { what: p.what, radius: p.radius, interval: stepsOf(p.seconds), cooldown: 0, max: p.max }))
}
// A workshop that wears out tools keeps a few on its shelf too.
const tools = kind.wear ? ["tools" as const] : []
@@ -69,7 +69,7 @@ export const rolesOf = (kind: Kind, rules: Rules = shippedRules) => {
if (kind.carriers) roles.push(Game.Command.entry(Carriers, { count: kind.carriers }))
if (kind.service) {
const s = kind.service
- roles.push(Game.Command.entry(Service, { service: s.service, interval: ticks(s.seconds), cooldown: 0, range: s.range }))
+ roles.push(Game.Command.entry(Service, { service: s.service, interval: stepsOf(s.seconds), cooldown: 0, range: s.range }))
}
// The town hall neither burns nor wears.
if (kind.id !== "townhall") roles.push(...wearOf(rules))
diff --git a/src/content.ts b/src/content.ts
index 54ecda1..0d1128c 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -2,13 +2,38 @@
* What the town is made of, as plain data: goods, the buildings that
* gather, make, store, and hand them out, and the tiers of homes. Costs,
* upkeep, and taxes are in coins; durations in seconds, turned into whole
- * simulation steps by `ticks`. `archetypes.ts` turns each entry into the
- * components an entity is spawned with; nothing here knows about the ECS.
+ * simulation steps by `Clock.duration` (literals) and `stepsOf` (data).
+ * `archetypes.ts` turns each entry into the components an entity is spawned
+ * with; nothing here knows about the ECS beyond its clock's step.
*/
+import { Clock } from "@typeonce/ritmo"
-/** The simulation's fixed step. */
-export const STEP_SECONDS = 1 / 60
-export const ticks = (seconds: number): number => Math.round(seconds / STEP_SECONDS)
+/** The simulation's fixed step: 60 a second, shared by the page's loop, the replay recorder, and the `Time` clock. */
+export const step = Clock.hz(60)
+
+/**
+ * Seconds read from data (a kind's, a rule's) as whole steps. A span
+ * shorter than one step, which `Clock.durationRaw` refuses, is no wait at
+ * all: 0 steps (`resolveRules` refuses a kind's `seconds` that short, so a
+ * period is always at least one step).
+ */
+export const stepsOf = (seconds: number): number => {
+ const span = Clock.durationRaw(step, seconds)
+ return span.ok ? Clock.steps(span.value) : 0
+}
+
+/**
+ * A period the rules give in whole steps (patchable, so data) as a clock
+ * duration for `Clock.every`; refused when under one step (a period of 0
+ * never comes round, as `tick % 0` never did).
+ */
+export const periodOf = (steps: number) => Clock.durationRaw(step, steps / step.hz)
+
+/** A cadence supplied as whole steps by the game's rules; invalid periods never fire. */
+export const every = (time: Clock.Time<60>, steps: number): boolean => {
+ const period = periodOf(steps)
+ return period.ok && Clock.every(time, period.value)
+}
// ── Goods ─────────────────────────────────────────────────────────────────
@@ -66,7 +91,7 @@ export const foods: ReadonlyArray<GoodId> = ["fish", "smoked", "bread"]
* Every `SPOIL_TICKS`, each shelf loses its share of what it holds.
*/
export const spoils: Partial<Record<GoodId, number>> = { fish: 180, bread: 300 }
-export const SPOIL_TICKS = 600
+export const SPOIL_TICKS = Clock.steps(Clock.duration(step, 10))
// ── Buildings ─────────────────────────────────────────────────────────────
@@ -217,7 +242,7 @@ export const asUpgraded = <K extends Kind>(kind: K, level: number): 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)
+export const WORKS_TICKS = Clock.steps(Clock.duration(step, 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
@@ -548,9 +573,9 @@ export const home = {
readonly rise: Kind["cost"]
}>>,
/** A resident moves in (or out) this often. */
- settle: ticks(3),
+ settle: Clock.steps(Clock.duration(step, 3)),
/** How long each need stays met after a walker's visit: cloth and faith last longer than a meal. */
- lasts: { food: ticks(90), bread: ticks(120), cloth: ticks(240), faith: ticks(180), furniture: ticks(300) } as Readonly<Record<Need, number>>,
+ lasts: { food: Clock.steps(Clock.duration(step, 90)), bread: Clock.steps(Clock.duration(step, 120)), cloth: Clock.steps(Clock.duration(step, 240)), faith: Clock.steps(Clock.duration(step, 180)), furniture: Clock.steps(Clock.duration(step, 300)) } as Readonly<Record<Need, number>>,
/** Where nobody wants to live: the desirability the map's legend calls squalid. */
squalid: -5,
/**
@@ -661,7 +686,7 @@ export const risk = {
/** Heating through a hard winter. */
winter: 6,
/** How long a blaze burns before the house is lost. */
- burns: ticks(20),
+ burns: Clock.steps(Clock.duration(step, 20)),
/** A burning house sets a neighbour alight, each second: this chance, and up to `spread` more for a neighbour at the top of its own meter. */
catches: 0.03,
spread: 0.12,
@@ -679,7 +704,7 @@ export const risk = {
/** Still water within two cells. */
water: 3,
/** How long a sickness lasts if no physician comes; meanwhile the home holds `sickly` as many. */
- lasts: ticks(60),
+ lasts: Clock.steps(Clock.duration(step, 60)),
sickly: 0.5,
/** Each second, the chance it reaches a home within two cells: raising its risk by `contagion` (a home a physician calls on shrugs it off). */
spreads: 0.04,
@@ -708,7 +733,7 @@ export const risk = {
export const CONDITION_MAX = 1000
export const condition = {
/** A point lost every `every` steps: from new to run down in about 33 minutes, and fallen down in 67, unmended. */
- every: ticks(4),
+ every: Clock.steps(Clock.duration(step, 4)),
/** Below this, a builder mends it as they pass (after about 23 minutes without repair). */
mend: 650,
/** Below this, it works at half pace, and its fire risk rises. */
@@ -723,12 +748,12 @@ export const needTitle: Readonly<Record<Need, string>> = { food: "food", bread:
// ── The town ──────────────────────────────────────────────────────────────
/** How long anything takes to go up once its materials are in. */
-export const BUILD_TICKS = ticks(2.4)
+export const BUILD_TICKS = Clock.steps(Clock.duration(step, 2.4))
/** Taxes are collected and upkeep paid this often. */
-export const LEDGER_TICKS = ticks(10)
+export const LEDGER_TICKS = Clock.steps(Clock.duration(step, 10))
export const ROAD_COST = 2
/** Trees and fields are ready to harvest once this grown. */
-export const GROWN = { tree: ticks(40), field: ticks(20) }
+export const GROWN = { tree: Clock.steps(Clock.duration(step, 40)), field: Clock.steps(Clock.duration(step, 20)) }
/** The most a rock holds (see `lands` for how much each starts with). */
export const ROCK_AMOUNT = 40
/**
@@ -736,13 +761,13 @@ export const ROCK_AMOUNT = 40
* stone (or ore) this often, so a quarry or mine beside it keeps going at
* about a third of its pace instead of stopping for good.
*/
-export const FACE_TICKS = ticks(90)
+export const FACE_TICKS = Clock.steps(Clock.duration(step, 90))
/**
* A cell of water fished rests this long before it gives another catch,
* so a fishery needs a good stretch of shore to itself to work at full
* pace, and fisheries crowded on one lake share its fish.
*/
-export const RESTOCK_TICKS = ticks(40)
+export const RESTOCK_TICKS = Clock.steps(Clock.duration(step, 40))
// ── The charter: what a new town is founded on ────────────────────────────
@@ -834,7 +859,7 @@ export const winters: Readonly<Record<WinterId, { readonly title: string; readon
hard: { title: "hard", share: WINTER_SHARE * 1.5, fishing: 0.4, heating: true, chance: 0.25 }
}
/** The almanac warns of winter this many steps before it comes. */
-export const WINTER_WARNING = ticks(60)
+export const WINTER_WARNING = Clock.steps(Clock.duration(step, 60))
/**
* Running a town costs more the bigger it gets, and it is reckoned by the
@@ -968,4 +993,4 @@ export const ranks: ReadonlyArray<{
export const TOWN_RANK = 2
/** The town's history: a sample this often. */
-export const HISTORY_TICKS = ticks(15)
+export const HISTORY_TICKS = Clock.steps(Clock.duration(step, 15))
diff --git a/src/dev/devtools.ts b/src/dev/devtools.ts
index 60461d2..6f08d65 100644
--- a/src/dev/devtools.ts
+++ b/src/dev/devtools.ts
@@ -5,11 +5,11 @@
* `vite.config.ts`) when a step fails, when an invariant breaks, or when the
* monitor's "Save replay" button is pressed. See PLAYTEST.md.
*/
-import type { HostClock } from "@typeonce/bevy-ts"
-import { Invariant, Monitor, Replay } from "@typeonce/bevy-ts-devtools"
-import * as ReplayViteSink from "@typeonce/bevy-ts-devtools/ReplayViteSink"
+import type { HostClock } from "@typeonce/ritmo"
+import { Invariant, Monitor, Replay } from "@typeonce/ritmo-devtools"
+import * as ReplayViteSink from "@typeonce/ritmo-devtools/ReplayViteSink"
-import { STEP_SECONDS } from "../content.ts"
+import { step } from "../content.ts"
import { present } from "../present.ts"
import { Building, Game, Root, Treasury } from "../schema.ts"
import { simulate } from "../sim/index.ts"
@@ -55,7 +55,7 @@ export const attachDevtools = (host: DevtoolsHost) => {
schedule: simulate,
name: "simulate",
keep: 60,
- stepSeconds: STEP_SECONDS,
+ step,
sink: ReplayViteSink.make({ fetch: host.fetch, onError: (error) => console.warn("The replay could not reach the dev server", error) }),
hostClock: host.wallClock,
saveOn: { failure: true, invariants: host.demo ? [CoinsAreWhole, FewerThanTenBuildings] : [CoinsAreWhole] }
diff --git a/src/host.ts b/src/host.ts
index bfd3d33..542d492 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -30,7 +30,7 @@ import {
needTitle,
LEDGER_TICKS,
RESERVE_MAX,
- STEP_SECONDS,
+ step,
TRADE_LOAD,
ROAD_COST,
sizeIds,
@@ -1114,7 +1114,7 @@ export const createHost = async (
reserve.input.title = "How much of each good the town keeps: it sells only beyond this, and buys only up to it"
store.append(reserveLine, reserve.input, el("p", "effect", "of each good: sold only above this, bought only up to it"))
/** Collections a minute: the traders come at every ledger. */
- const perMinute = 60 / (LEDGER_TICKS * STEP_SECONDS)
+ const perMinute = 60 / (LEDGER_TICKS * step.dt)
const goodRows = goodIds.map((g) => {
const line = el("div", "trade-row")
const name = el("span", "label")
diff --git a/src/main.ts b/src/main.ts
index 075085e..e068a87 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -4,12 +4,12 @@ import { resolveRules } from "./rules/config.ts"
* bevy-ts ECS with a 3D view. The simulation runs on a fixed step;
* the views follow once a frame.
*/
-import { HostClock, Result } from "@typeonce/bevy-ts"
+import { HostClock, Result } from "@typeonce/ritmo"
import { Effect } from "effect"
-import { BrowserHostClock, FixedLoop } from "@typeonce/bevy-ts-browser"
+import { BrowserHostClock, FixedLoop } from "@typeonce/ritmo-browser"
import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./render3d/views.ts"
-import { lands, sizes, STEP_SECONDS } from "./content.ts"
+import { lands, sizes, step } from "./content.ts"
import { createHost, type Persistence } from "./host.ts"
import { present } from "./present.ts"
import { browserStorage, describe, fileOf, latest, loadLatest, loadText, save, Storage, World } from "./save.ts"
@@ -45,7 +45,7 @@ const start = async () => {
(text) => (arriving = text),
(error: unknown) => visitFailed(error instanceof Error ? error.message : "Could not open that town")
)
- const clock = { deltaSeconds: STEP_SECONDS, elapsed: 0 }
+ const clock = { deltaSeconds: step.dt, elapsed: 0 }
const buildingNodes = stage.registry<BuildingView>(),
houseNodes = stage.registry<HouseView>(),
@@ -90,7 +90,7 @@ const start = async () => {
// `town.runtime.snapshot()`, and `town.advance(seconds)` to fast-forward the simulation.
if (import.meta.env.DEV) {
const advance = (seconds: number) => {
- for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)
+ for (let i = 0; i < Math.round(seconds / step.dt); i++) runtime.tick(simulate)
}
Object.assign(window, { town: { ui, runtime, advance, view: stage } })
if (runtime.debug !== undefined) {
@@ -161,7 +161,7 @@ const start = async () => {
let settling = false
const loop = FixedLoop.start({
source: FixedLoop.source((onTick) => stage.subscribe(onTick)),
- stepSeconds: STEP_SECONDS,
+ step,
maxFrameSeconds: 0.25,
maxStepsPerFrame: 4,
// The town runs at the chosen speed; it waits while paused, while the
diff --git a/src/mapgen.ts b/src/mapgen.ts
index 7ae04a6..6f88768 100644
--- a/src/mapgen.ts
+++ b/src/mapgen.ts
@@ -8,7 +8,7 @@ import { shippedRules, type Rules } from "./rules/config.ts"
* the rest).
* Pure: the same charter always makes the same land.
*/
-import * as Random from "@typeonce/bevy-ts-math/Random"
+import * as Random from "@typeonce/ritmo-math/Random"
import { GROWN, type CharterValue } from "./content.ts"
import { DIRS, key } from "./grid.ts"
diff --git a/src/present.ts b/src/present.ts
index 04f4d7d..d64ec37 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -4,7 +4,7 @@
* panel, tooltip, top bar, map views, and the town's alerts are filled in;
* and the views follow the world.
*/
-import { RenderSync } from "@typeonce/bevy-ts-render"
+import { RenderSync } from "@typeonce/ritmo-render"
import { hazardStrength } from "./render3d/surface-state.ts"
import { appealAt, appealParts, buildingSource, homeSource, landSource, parkSources, parksOf, type AppealSource, type ParkCell, type ParkValue } from "./appeal.ts"
@@ -12,7 +12,7 @@ import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "./art.t
import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, RuinView } from "./render3d/views.ts"
import type { DoorSet, OverlayCell } from "./render3d/models.ts"
import {
- amounts, BUILD_TICKS, builtCost, COMMUTE, provisions, RESTOCK_TICKS, STEP_SECONDS, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,
+ amounts, BUILD_TICKS, builtCost, COMMUTE, provisions, RESTOCK_TICKS, step, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,
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"
@@ -97,7 +97,7 @@ import { approvalTarget } from "./rules/approval.ts"
import { salvageOf, salvageText, withWorks } from "./rules/salvage.ts"
import { rockBlocks, type RockPart } from "./render3d/rock-blocks.ts"
import { courseCount, GUIDE_QUIET, guideDone, guideStep, guideSteps, lockedNote, upcoming, type GuideFacts, type GuideFocus } from "./rules/guide.ts"
-import { anA, TAX_STEPS, ticks } from "./content.ts"
+import { anA, TAX_STEPS, stepsOf } from "./content.ts"
const cellAt = (at: Point): Point => {
return { x: Math.floor(at.x), y: Math.floor(at.y) }
@@ -162,7 +162,7 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: C
case "starved":
if (kind.gathers?.source === "water")
return growing
- ? { label: "no fish", why: `the water in reach is fished out: each stretch rests ${Math.round(RESTOCK_TICKS * STEP_SECONDS)} s after a catch`, fix: { text: "give it a longer shore of its own, or fewer fisheries on this water" } }
+ ? { label: "no fish", why: `the water in reach is fished out: each stretch rests ${Math.round(RESTOCK_TICKS * step.dt)} s after a catch`, fix: { text: "give it a longer shore of its own, or fewer fisheries on this water" } }
: { label: "no water", why: `no water within ${kind.gathers.radius} cells`, fix: { text: "rebuild it by the shore" } }
if (kind.gathers && growing && (kind.gathers.source === "stone" || kind.gathers.source === "ore"))
return { label: "worked out", why: `the worked faces in reach give a little ${kind.gathers.source} now and then`, fix: { text: `build it by fresh rock, or buy ${kind.gathers.source} in the [town] panel` } }
@@ -353,14 +353,14 @@ const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {
/** When each workshop began waiting for its input: a shelf runs empty for a moment all the time, so the ticker only says so after `ALERT_PATIENCE`. */
const starvedSince = new Map<number, number>()
-const ALERT_PATIENCE = ticks(30)
+const ALERT_PATIENCE = stepsOf(30)
/** Since when the store has held no food (`null`: it has some). Fish comes in and goes out in handfuls, so the ticker waits `HUNGER_PATIENCE` before saying so. */
let emptySince: number | null = null
/** Once said, it stays said a while, so a handful of fish arriving does not flick it off and on. */
let hungryUntil = 0
/** Why each building's upgrade is needed now, by its id, reckoned once a second (see `upgradesWanted`). */
let wanted: { at: number; why: Map<number, string> } = { at: -1, why: new Map() }
-const HUNGER_PATIENCE = ticks(20)
+const HUNGER_PATIENCE = stepsOf(20)
/** A view's colour over a model: pale, so the ink still reads. */
const TINT = { good: 0xbcd2ee, fair: 0xf3e3a8, bad: 0xf2b9a0, cool: 0xdccbe8, mark: 0xd5dad3, settlers: 0xead7bd, fine: 0xa9c4e8, plain: 0xffffff }
const needIcons = { food: "food", bread: "bread", cloth: "cloth", faith: "faith", furniture: "furniture" } as const
@@ -430,7 +430,7 @@ export const Interact = Game.System(
const 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().tick
+ const tick = resources.time.get().step
const buildings = queries.buildings.each()
const houses = queries.houses.each()
const ruins = queries.ruins.each()
@@ -827,7 +827,7 @@ export const Interact = Game.System(
* homes without faith; a fire watch with homes on its streets at high fire risk.
*/
const upgradesWanted = (): ReadonlyMap<number, string> => {
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
if (Math.floor(tick / 60) === wanted.at) return wanted.why
const why = new Map<number, string>()
const standingRows = buildings.filter((r) => !r.data.site.present && !r.data.rising.present && !maybe(r.data.works))
@@ -1927,7 +1927,7 @@ export const Animate = Game.System(
const emphasis = (id: number): Emphasis => (danger && hover === id ? "danger" : "normal")
const dt = services.clock.deltaSeconds
// Fish where the water would give a catch now; none where it rests after one.
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
services.stage.setFish(queries.water.each().filter(({ data }) => tick - data.water.get().fished >= RESTOCK_TICKS).map(({ data }) => data.tile.get()))
for (const { entity, data } of queries.buildings.each()) {
diff --git a/src/render3d/scene.ts b/src/render3d/scene.ts
index da807fe..0820aa3 100644
--- a/src/render3d/scene.ts
+++ b/src/render3d/scene.ts
@@ -1,5 +1,5 @@
import * as THREE from "three"
-import { NodeRegistry } from "@typeonce/bevy-ts-render"
+import { NodeRegistry } from "@typeonce/ritmo-render"
import { buildAsset, floorScale, vertex3, type BuiltAsset } from "../asset-lab/renderer.ts"
import { house } from "../asset-lab/homes.ts"
import { makeBuilding } from "../asset-lab/buildings.ts"
diff --git a/src/rules/config.ts b/src/rules/config.ts
index bf53c12..e127dad 100644
--- a/src/rules/config.ts
+++ b/src/rules/config.ts
@@ -12,12 +12,12 @@ const inputs = () => ({
risk: content.risk, condition: content.condition, winters: content.winters,
admin: content.admin, mood: content.mood, crown: content.crown, market: content.market, fate: content.fate, ranks: content.ranks,
spoils: content.spoils, trade: content.trade, tradeLoad: content.TRADE_LOAD, transport,
- stepSeconds: content.STEP_SECONDS, ledgerTicks: content.LEDGER_TICKS, spoilTicks: content.SPOIL_TICKS,
+ stepSeconds: content.step.dt, ledgerTicks: content.LEDGER_TICKS, spoilTicks: content.SPOIL_TICKS,
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, worksTicks: content.WORKS_TICKS, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,
- spreadTicks: content.ticks(1.5), growTicks: 10
+ grown: content.GROWN, faceTicks: content.FACE_TICKS, restockTicks: content.RESTOCK_TICKS, worksTicks: content.WORKS_TICKS, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.stepsOf(0.5), riskTicks: 60,
+ spreadTicks: content.stepsOf(1.5), growTicks: 10
})
type NumericData<T> = T extends number ? number : T extends object ? { readonly [K in keyof T]: NumericData<T[K]> } : T
diff --git a/src/rules/seasons.ts b/src/rules/seasons.ts
index 7cbd495..09755d1 100644
--- a/src/rules/seasons.ts
+++ b/src/rules/seasons.ts
@@ -4,7 +4,7 @@ import { ruleTicks, shippedRules, type Rules } from "./config.ts"
// ── Time ──────────────────────────────────────────────────────────────────
/** Steps since the town was founded. */
-export const elapsed = (time: { readonly tick: number }, charter: { readonly founded: number }) => time.tick - charter.founded
+export const elapsed = (time: { readonly step: number }, charter: { readonly founded: number }) => time.step - charter.founded
export const termTicks = (charter: { readonly term: number }, rules: Rules = shippedRules) => ruleTicks(charter.term * 60, rules)
export const yearTicks = (charter: { readonly term: number }, rules: Rules = shippedRules) => Math.round(termTicks(charter, rules) / rules.yearsPerTerm)
diff --git a/src/save.ts b/src/save.ts
index d2ab0ae..19ed249 100644
--- a/src/save.ts
+++ b/src/save.ts
@@ -18,9 +18,10 @@ export const SAVE_FORMAT = "inkline-town/save"
* winters). 4: parks and patrols. 5: the grudge over taxes, and where each piece of news happened.
* 6: how much of each good may be traded at a collection. 7: the mayor's guide. 8: terms that follow one
* another, the town's rank, and upgraded buildings.
- * Version 4 to 8 saves are carried forward (see `carry`); older ones cannot be loaded.
+ * 10: fixed-step Clock values and runtime snapshot format 2.
+ * Version 4 to 9 saves are carried forward (see `carry`); older ones cannot be loaded.
*/
-export const SAVE_VERSION = 9
+export const SAVE_VERSION = 10
/**
* Fills in what a save from an earlier version lacks, so a town in progress
@@ -35,10 +36,18 @@ export const SAVE_VERSION = 9
* Anything else is left to the world's own validation.
*/
const carry = (version: number, world: unknown): unknown | null => {
- if (version < 4 || version > 8 || typeof world !== "object" || world === null) return null
- const w = world as { resources?: Record<string, unknown>; entities?: Array<{ components?: Record<string, unknown> }> }
+ if (version < 4 || version > 9 || typeof world !== "object" || world === null) return null
+ const w = world as { version?: number; scopes?: Record<string, unknown>; resources?: Record<string, unknown>; entities?: Array<{ components?: Record<string, unknown> }> }
const r = w.resources
if (!r || typeof r !== "object") return null
+ // Town never used entity scopes before this format. Its old clock counted
+ // the same 60 Hz steps under `tick`; preserve that count exactly.
+ if (w.version === 1) { w.version = 2; w.scopes = {} }
+ const time = r["Town/Time"]
+ if (typeof time === "object" && time !== null && "tick" in time && typeof time.tick === "number") {
+ r["Town/Time"] = { step: time.tick, hz: 60, dt: time.tick > 0 ? 1 / 60 : 0 }
+ }
+ if (version === 9) return w
// 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"]
@@ -218,7 +227,7 @@ export const read = (slot: Slot) =>
const parsed = yield* decodeFile(raw).pipe(Effect.mapError((e) => new Unreadable({ slot, reason: e.message })))
// The first charter saves were the world alone.
if (typeof parsed === "object" && parsed !== null && "entities" in parsed && !("format" in parsed)) {
- return { format: SAVE_FORMAT, version: SAVE_VERSION, slot, savedAt: 0, title: "an earlier save", world: parsed } satisfies SaveFile
+ return { format: SAVE_FORMAT, version: SAVE_VERSION, slot, savedAt: 0, title: "an earlier save", world: carry(9, parsed) ?? parsed } satisfies SaveFile
}
const version = (parsed as { version?: unknown } | null)?.version
if (typeof version === "number" && version !== SAVE_VERSION) {
diff --git a/src/schema.ts b/src/schema.ts
index 4a4c602..59f89cb 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -11,9 +11,10 @@
* Saved components and resources are constructed with a validator, so the
* whole world snapshots to plain data and loads back checked.
*/
-import { Decode, Descriptor, Schema } from "@typeonce/bevy-ts"
-import type { OptionalReadCell } from "@typeonce/bevy-ts/Query"
-import type { NodeRegistry } from "@typeonce/bevy-ts-render"
+import { Clock as SimulationClock, Decode, Descriptor, Schema } from "@typeonce/ritmo"
+import type { OptionalReadCell } from "@typeonce/ritmo/Query"
+import type { NodeRegistry } from "@typeonce/ritmo-render"
+import { step } from "./content.ts"
import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./render3d/views.ts"
import type { GameScene } from "./render3d/scene.ts"
@@ -192,8 +193,8 @@ export const { relation: FieldOf } = Descriptor.Hierarchy("Town/FieldOf", "Town/
// ── Resources ─────────────────────────────────────────────────────────────
-export const Time = Descriptor.ConstructedResource(Decode.struct({ tick: integer }))("Town/Time")
-/** The deterministic random state (see `@typeonce/bevy-ts-math/Random`). */
+export const Time = SimulationClock.resource("Town/Time", step)
+/** The deterministic random state (see `@typeonce/ritmo-math/Random`). */
export const Rng = Descriptor.ConstructedResource(integer)("Town/Rng")
export const Treasury = Descriptor.ConstructedResource(Decode.struct({ coins: integer }))("Town/Treasury")
/** The last collection's taxes, trade (sold less bought), upkeep, and administration, per minute. */
diff --git a/src/sim/decay.ts b/src/sim/decay.ts
index c42ea49..e23e2dc 100644
--- a/src/sim/decay.ts
+++ b/src/sim/decay.ts
@@ -5,16 +5,16 @@ import { spoilExpectation } from "../rules/decay.ts"
* shelf, slower in a granary. The pantry keeps count of what the town ate
* and what rotted, a minute at a time.
*/
-import * as Random from "@typeonce/bevy-ts-math/Random"
+import * as Random from "@typeonce/ritmo-math/Random"
import { RuinParts, ruinDraft } from "../archetypes.ts"
-import { foods, goodIds, ticks } from "../content.ts"
+import { foods, goodIds, stepsOf } from "../content.ts"
import { counted, placeName } from "../places.ts"
import { Building, Burning, Charter, Chronicle, Condition, Game, Rules, House, Inventory, Pantry, Recipe, Rising, Rng, Site, Staff, Tile, Time, maybe } from "../schema.ts"
import { elapsed, write } from "./shared.ts"
/** The pantry warns of rotting food at most this often. */
-const ROT_WARNING = ticks(5 * 60)
+const ROT_WARNING = stepsOf(5 * 60)
export const Decay = Game.System(
"Town/Decay",
@@ -43,7 +43,7 @@ export const Decay = Game.System(
const rules = services.rules
const { kinds, condition: wear, spoils, spoilTicks: SPOIL_TICKS } = rules
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
const t = elapsed(resources.time.get(), resources.charter.get())
// Wear: a point every `wear.every` steps; at nothing it falls down.
diff --git a/src/sim/edits.ts b/src/sim/edits.ts
index ee819a3..2dee034 100644
--- a/src/sim/edits.ts
+++ b/src/sim/edits.ts
@@ -7,8 +7,8 @@
* Once the term has ended, only a new town, or another term, is taken.
*/
import { BuildingParts, buildingDraft, houseDraft, HouseParts, houseStart, ParkParts, parkDraft, RoadParts, roadDraft, RockParts, rockDraft, RoleParts, rolesOf, StartParts, startOf, TreeParts, treeDraft, WaterParts, waterDraft } from "../archetypes.ts"
-import * as Random from "@typeonce/bevy-ts-math/Random"
-import { amounts, anA, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, ticks, total, upgradeAt, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"
+import * as Random from "@typeonce/ritmo-math/Random"
+import { amounts, anA, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, stepsOf, 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"
@@ -474,7 +474,7 @@ export const ApplyEdits = Game.System(
const stock: Amounts = amounts(richness.stock)
commands.insert(id, Game.Command.entry(TownHall, {}), Game.Command.entry(Status, "idle"), Game.Command.entry(Inventory, { stock, accepts: goodIds, cap: hall.holds?.cap ?? 60 }))
coins = richness.coins
- const founded = resources.time.get().tick
+ const founded = resources.time.get().step
// The almanac: each year's winter, from the seed (on its own stream, so the land's randomness is untouched).
const almanac = Random.make((charter.seed ^ 0x5a17c3) >>> 0)
resources.charter.set({ ...charter, founded, winters: rollWinters(() => almanac.next(), rules) })
diff --git a/src/sim/hazards.ts b/src/sim/hazards.ts
index e0b0567..e8fd25a 100644
--- a/src/sim/hazards.ts
+++ b/src/sim/hazards.ts
@@ -1,3 +1,4 @@
+import { every } from "../content.ts"
import { near, riskIncrements } from "../rules/risks.ts"
/**
* The neighbourhood and its dangers. Every so often the town's desirability
@@ -9,7 +10,7 @@ import { near, riskIncrements } from "../rules/risks.ts"
* home left derelict. A fire watch sends firefighters running to any blaze
* (`Douse`): when they arrive, that house is lost but the fire is out.
*/
-import * as Random from "@typeonce/bevy-ts-math/Random"
+import * as Random from "@typeonce/ritmo-math/Random"
import { appealGrid, appealAt, buildingSource, homeSource, landSource, parkSources, type AppealSource } from "../appeal.ts"
import { RuinParts, ruinDraft } from "../archetypes.ts"
@@ -43,7 +44,7 @@ export const Appraise = Game.System(
const rules = services.rules
const { appeal, condition: wear } = rules
- if (resources.time.get().tick % appeal.every !== 0 && resources.appeal.get().cells.length > 0) return
+ if (!every(resources.time.get(), appeal.every) && 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, maybe(data.upgraded)?.level ?? 0)
@@ -121,7 +122,7 @@ export const Hazards = Game.System(
const rules = services.rules
const { kinds, goods, risk, winters, riskMax: RISK_MAX, riskTicks: RISK_TICKS } = rules
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
if (tick % RISK_TICKS !== 0) return
const charter = resources.charter.get()
const t = elapsed(resources.time.get(), charter)
diff --git a/src/sim/headless.ts b/src/sim/headless.ts
index 719cfe9..00592a0 100644
--- a/src/sim/headless.ts
+++ b/src/sim/headless.ts
@@ -4,10 +4,10 @@
* this, pushing the same edits the page does and reading the world through
* the same snapshots it saves.
*/
-import { HostClock } from "@typeonce/bevy-ts"
-import type * as Replay from "@typeonce/bevy-ts-devtools/Replay"
+import { HostClock } from "@typeonce/ritmo"
+import type * as Replay from "@typeonce/ritmo-devtools/Replay"
-import { STEP_SECONDS, type CharterValue } from "../content.ts"
+import { step as simulationStep, type CharterValue } from "../content.ts"
import { resolveRules, type Rules as RuleInputs } from "../rules/config.ts"
import { Edits, Game, Rules, Toast } from "../schema.ts"
import { emptyPreview, type Edit, type UiValue } from "../ui.ts"
@@ -57,7 +57,7 @@ export const replayTarget = (playback: Replay.Playback) => {
}
/**
- * What `bevy-ts-devtools lint src/sim/headless.ts` checks (`pnpm lint:game`,
+ * What `ritmo-devtools lint src/sim/headless.ts` checks (`pnpm lint:game`,
* part of `pnpm check`): the simulation on a debug runtime, and the page's
* `present` schedule described without running (it needs the renderer).
*/
@@ -73,10 +73,10 @@ export const lintTarget = async () => {
return { runtime: made.value, schedules: { simulate }, describe: { present } }
}
-export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void; readonly rules?: RuleInputs } = {}) => {
+export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void; readonly rules?: RuleInputs; readonly hostClock?: HostClock.HostClock } = {}) => {
const toast = options.toast ?? (() => {})
const ui = blankUi(charter, toast)
- const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Edits, editsOf(ui)), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources() })
+ const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Edits, editsOf(ui)), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources(), debug: { hostClock: options.hostClock ?? HostClock.test() } })
if (!made.ok) throw new Error(`The town could not start: ${JSON.stringify(made.error)}`)
const runtime = made.value
const step = () => {
@@ -90,7 +90,7 @@ export const headless = (charter: CharterValue, options: { readonly toast?: (mes
runtime,
/** Runs the town on for `seconds` of game time. */
run: (seconds: number) => {
- for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) step()
+ for (let i = 0; i < Math.round(seconds / simulationStep.dt); i++) step()
},
/** Pushes edits, applied on the next step. */
edit: (...edits: ReadonlyArray<Edit>) => {
diff --git a/src/sim/index.ts b/src/sim/index.ts
index 267dc54..a094b95 100644
--- a/src/sim/index.ts
+++ b/src/sim/index.ts
@@ -2,7 +2,8 @@
* The simulation, one fixed step at a time. Nothing here touches the
* renderer, so it runs headless too.
*/
-import { amounts, defaultCharter, goodIds, TRADE_LOAD } from "../content.ts"
+import { Clock } from "@typeonce/ritmo"
+import { amounts, defaultCharter, goodIds, step, TRADE_LOAD } from "../content.ts"
import { Game, Time } from "../schema.ts"
import { ApplyEdits } from "./edits.ts"
import { Deliver, Dispatch } from "./logistics.ts"
@@ -13,13 +14,7 @@ import { Collect, Households, TakeCensus } from "./town.ts"
import { SendWalkers, Walk, Wander } from "./walkers.ts"
import { AssignStaff, CountStock, Grow, IndexGrid, Plant, Raise, Spread, Work } from "./work.ts"
-export const AdvanceTime = Game.System(
- "Town/AdvanceTime",
- { resources: { time: Game.System.writeResource(Time) } },
- ({ resources }) => {
- resources.time.update((t) => ({ tick: t.tick + 1 }))
- }
-)
+export const AdvanceTime = Clock.system(Game, { name: "Town/AdvanceTime", resource: Time })
export const simulate = Game.Schedule(
AdvanceTime,
@@ -59,7 +54,7 @@ export const simulate = Game.Schedule(
/** The world's resources before any town is founded (a `newTown` edit fills them in). */
export const blankResources = () => ({
- Time: { tick: 0 },
+ Time: Clock.start(step),
Rng: 0x5eed,
Treasury: { coins: 0 },
Ledger: { taxes: 0, trade: 0, upkeep: 0, admin: 0 },
diff --git a/src/sim/logistics.ts b/src/sim/logistics.ts
index c81feed..2d2307e 100644
--- a/src/sim/logistics.ts
+++ b/src/sim/logistics.ts
@@ -1,3 +1,4 @@
+import { every } from "../content.ts"
import { transport } from "../rules/config.ts"
import { wantsBurgherGoods, wantsCitizenGoods } from "../rules/households.ts"
import { appealAt } from "../appeal.ts"
@@ -60,7 +61,7 @@ export const Dispatch = Game.System(
const rules = services.rules
const { kinds, goods, spoils, toolStock: TOOL_STOCK } = rules
- if (resources.time.get().tick % DISPATCH_TICKS !== 0) return
+ if (!every(resources.time.get(), DISPATCH_TICKS)) return
const grid = resources.grid.get()
const out = new Map<number, number>()
const incoming = new Map<string, number>()
diff --git a/src/sim/term.ts b/src/sim/term.ts
index dd8beea..5f6e287 100644
--- a/src/sim/term.ts
+++ b/src/sim/term.ts
@@ -5,8 +5,8 @@ import { shippedRules } from "../rules/config.ts"
* town's approval follows how it is treated, the town's history is kept,
* the town rises through its ranks, and the term ends: lost, or run out.
*/
-import { crown, HISTORY_TICKS, ticks, WINTER_WARNING, type GoodId } from "../content.ts"
-import * as Random from "@typeonce/bevy-ts-math/Random"
+import { crown, HISTORY_TICKS, stepsOf, WINTER_WARNING, type GoodId } from "../content.ts"
+import * as Random from "@typeonce/ritmo-math/Random"
import { Building, Census, Charter, Chronicle, Crown, Fate, Game, Rules, History, House, Inventory, Ledger, Mood, Pantry, Paused, Policy, Recipe, Rising, Rng, Site, Stock, Storage, Time, Treasury, TownHall, Upgraded, maybe } from "../schema.ts"
import { elapsed, seasonAt, termTicks, write } from "./shared.ts"
@@ -98,7 +98,7 @@ export const Requests = Game.System(
const charter = resources.charter.get()
const t = elapsed(resources.time.get(), charter)
const c = resources.crown.get()
- const remembered = c.snubs.filter((at) => t - at < ticks(crown.memory * 60))
+ const remembered = c.snubs.filter((at) => t - at < stepsOf(crown.memory * 60))
if (remembered.length !== c.snubs.length) resources.crown.set({ ...c, snubs: remembered })
if (c.open && t >= c.due) {
@@ -163,7 +163,7 @@ export const Approve = Game.System(
const rules = services.rules
const t = elapsed(resources.time.get(), resources.charter.get())
- if (t % ticks(10) !== 0) return
+ if (t % stepsOf(10) !== 0) return
const policy = resources.policy.get()
const m = resources.mood.get()
const parts = approvalTarget(queries.homes.each().map(({ data }) => data.house.get()), policy,
@@ -240,7 +240,7 @@ export const Judge = Game.System(
const residents = census.settlers + census.citizens
const net = steadyNet(resources.history.get().samples, ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin)
const note = (text: string, alarm = false) => write(resources.chronicle, t, text, alarm)
- const minutes = (n: number) => ticks(n * 60)
+ const minutes = (n: number) => stepsOf(n * 60)
const next = { ...f, peak: Math.max(f.peak, residents) }
for (const mark of [50, 100, 250, 500, 1000]) if (f.peak < mark && residents >= mark) note(`${mark} residents.`)
diff --git a/src/sim/town.ts b/src/sim/town.ts
index 33a3549..fac46df 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -1,3 +1,4 @@
+import { every } from "../content.ts"
import { tradeCollection } from "../rules/trade.ts"
/**
* The town: homes grow, level up, or empty depending on what reaches them;
@@ -145,7 +146,7 @@ export const Collect = Game.System(
const rules = services.rules
const { kinds, ledgerTicks: LEDGER_TICKS, pausedUpkeep: PAUSED_UPKEEP } = rules
- if (resources.time.get().tick % LEDGER_TICKS !== 0) return
+ if (!every(resources.time.get(), LEDGER_TICKS)) return
const grid = resources.grid.get()
const policy = resources.policy.get()
const hall = queries.halls.each()[0]
diff --git a/src/sim/walkers.ts b/src/sim/walkers.ts
index 54b574a..f38c28d 100644
--- a/src/sim/walkers.ts
+++ b/src/sim/walkers.ts
@@ -11,7 +11,7 @@ import { appealAt } from "../appeal.ts"
* planks and stone to mend — and walks home when its range is walked.
*/
-import { amounts, categoryColor, each, provisions, ticks, total, type Amounts } from "../content.ts"
+import { amounts, categoryColor, each, provisions, stepsOf, total, type Amounts } from "../content.ts"
import { DIRS, doors, isRoad, key, nearest, ownerAt, pathTo, reach, useAt } from "../grid.ts"
import { inside, type Point } from "../iso.ts"
import { Building, Burning, Condition, Figure, Game, Rules, Grid, Appeal, Handed, Patrol, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Roam, Route, Service, Sick, Site, Staff, Status, Tile, Time, WalkerOf, maybe, type HandedValue, type Status as StatusValue } from "../schema.ts"
@@ -42,7 +42,7 @@ export const Walk = Game.System(
},
({ queries, resources, commands, services }) => {
const grid = resources.grid.get()
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
const quicker = services.rules.pavedPace - 1
for (const { entity, data } of queries.walkers.each()) {
const route = data.route.get()
@@ -101,7 +101,7 @@ export const SendWalkers = Game.System(
const { kinds, apprentice: APPRENTICE } = rules
const grid = resources.grid.get()
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
const out = new Map<number, number>()
for (const { data } of queries.walkers.each()) out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
@@ -207,7 +207,7 @@ export const Wander = Game.System(
for (const row of queries.cared.each()) cared.set(row.entity.id, row)
let eaten = 0
// What each walker hands each home, for its building's last minute (see `Handed`).
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
const handed: Array<HandedValue["log"][number]> = []
for (const { entity, data } of walkers) {
@@ -296,7 +296,7 @@ export const Wander = Game.System(
}
if (eaten > 0) resources.pantry.update((p) => ({ ...p, eaten: p.eaten + eaten }))
// The last minute only; a log from another town (its clock behind this one's) is dropped.
- const kept = resources.handed.get().log.filter((l) => l.at <= tick && tick - l.at < ticks(60))
+ const kept = resources.handed.get().log.filter((l) => l.at <= tick && tick - l.at < stepsOf(60))
if (handed.length > 0 || kept.length !== resources.handed.get().log.length) resources.handed.set({ log: [...kept, ...handed] })
}
)
diff --git a/src/sim/work.ts b/src/sim/work.ts
index 9efdb4f..d72db53 100644
--- a/src/sim/work.ts
+++ b/src/sim/work.ts
@@ -1,3 +1,4 @@
+import { every } from "../content.ts"
import { wildTreeSpots, canSeedTree } from "../rules/land.ts"
/**
* Building and working: the grid and the town's stock are indexed, sites
@@ -5,10 +6,10 @@ import { wildTreeSpots, canSeedTree } from "../rules/land.ts"
* turn inputs (or the land) into goods, planters sow trees and fields, and
* what is sown grows.
*/
-import * as Random from "@typeonce/bevy-ts-math/Random"
+import * as Random from "@typeonce/ritmo-math/Random"
import { FieldParts, fieldDraft, TreeParts, treeDraft } from "../archetypes.ts"
-import { amounts, anA, asUpgraded, crewOf, goodIds, ticks, total, upgradeAt, worksNeeded, type Amounts, type Crew } from "../content.ts"
+import { amounts, anA, asUpgraded, crewOf, goodIds, stepsOf, 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
@@ -100,7 +101,7 @@ export const CountStock = Game.System(
const e = data.errand.get()
held[e.good] = held[e.good]! + e.count
}
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
const charter = resources.charter.get()
const town = `${charter.seed}:${charter.founded}`
const f = resources.flow.get()
@@ -115,7 +116,7 @@ export const CountStock = Game.System(
// Coins that came in other than by the collection (a reward, a refund) were made; any that went out are left over as used.
const other = treasury - f.coins.seen - f.coins.booked
const coins = { ...f.coins, made: f.coins.made + Math.max(0, other), seen: treasury, booked: 0 }
- if (tick - f.since < ticks(FLOW_SLICE)) {
+ if (tick - f.since < stepsOf(FLOW_SLICE)) {
resources.flow.set({ ...f, held: now, coins })
return
}
@@ -145,7 +146,7 @@ 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)
+const SELF_SUPPLY_TICKS = stepsOf(1)
/** Where a site's walls are once its materials are in: it goes on rising from here. */
export const SITE_SHARE = 0.35
@@ -183,7 +184,7 @@ export const Raise = Game.System(
// 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
+ const tick = resources.time.get().step
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.
@@ -210,10 +211,10 @@ export const Raise = Game.System(
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 (recipe && kind.recipe) commands.insert(entity.id, Game.Command.entry(Recipe, { ...recipe, period: stepsOf(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 }))
+ if (service && kind.service) commands.insert(entity.id, Game.Command.entry(Service, { ...service, interval: stepsOf(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 ${anA(upgradeAt(base, works.level)!.title.toLowerCase())}.`, true)
}
@@ -237,7 +238,7 @@ export const Raise = Game.System(
// ── Workers ───────────────────────────────────────────────────────────────
/** Workers are reassigned this often: residents move in and out every few seconds, no faster. */
-export const STAFF_TICKS = ticks(0.5)
+export const STAFF_TICKS = stepsOf(0.5)
/**
* Residents go to work at the workplaces within a commute of their home
@@ -272,7 +273,7 @@ export const AssignStaff = Game.System(
const rules = services.rules
const { kinds, commute: COMMUTE, staffTicks: STAFF_TICKS } = rules
- if (resources.time.get().tick % STAFF_TICKS !== 0) return
+ if (!every(resources.time.get(), STAFF_TICKS)) return
const grid = resources.grid.get()
const homes: Array<{ readonly id: number; readonly crew: Crew; left: number; readonly doors: ReadonlyArray<{ readonly x: number; readonly y: number }> }> = []
for (const { entity, data } of queries.homes.each()) {
@@ -376,7 +377,7 @@ export const Work = Game.System(
const made: Record<string, number> = {}
const grid = resources.grid.get()
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
const t = elapsed(resources.time.get(), resources.charter.get())
const season = seasonAt(t, resources.charter.get(), rules)
const fishing = season.severity ? winters[season.severity].fishing : 1
@@ -539,7 +540,7 @@ export const Plant = Game.System(
const grid = resources.grid.get()
const random = Random.make(resources.rng.get())
const sown = new Set<number>()
- const tick = resources.time.get().tick
+ const tick = resources.time.get().step
for (const { entity, data } of queries.planters.each()) {
const tile = data.tile.get()
const staff = data.staff.get()
@@ -591,7 +592,7 @@ export const Spread = Game.System(
const rules = services.rules
const { grown: GROWN, spreadTicks: SPREAD_TICKS } = rules
- if (resources.time.get().tick % SPREAD_TICKS !== 0) return
+ if (!every(resources.time.get(), SPREAD_TICKS)) return
const grid = resources.grid.get()
const random = Random.make(resources.rng.get())
const grown = queries.trees.each().filter(({ data }) => data.tree.get().growth >= GROWN.tree)
@@ -620,7 +621,7 @@ export const Grow = Game.System(
const rules = services.rules
const { grown: GROWN, growTicks: GROW_TICKS } = rules
- if (resources.time.get().tick % GROW_TICKS !== 0) return
+ if (!every(resources.time.get(), GROW_TICKS)) return
for (const { data } of queries.trees.each()) {
const growth = data.tree.get().growth
if (growth < GROWN.tree) data.tree.set({ growth: Math.min(GROWN.tree, growth + GROW_TICKS) })
diff --git a/test/clock-migration.test.ts b/test/clock-migration.test.ts
new file mode 100644
index 0000000..e131459
--- /dev/null
+++ b/test/clock-migration.test.ts
@@ -0,0 +1,36 @@
+import assert from "node:assert/strict"
+import { test } from "node:test"
+import { Effect } from "effect"
+import { HostClock } from "@typeonce/ritmo"
+import { Determinism } from "@typeonce/ritmo-devtools"
+import { load, memoryStorage, SAVE_FORMAT, SAVE_VERSION, Storage, World } from "../src/save.ts"
+import { headless } from "../src/sim/headless.ts"
+import { simulate } from "../src/sim/index.ts"
+
+test("version 9 saves retain the exact 60 Hz step count and load as snapshot format 2", () => {
+ const town = headless({ size: "small", term: 45, land: "fair", seed: 7 })
+ town.run(1)
+ const current = town.snapshot()
+ const count = current.resources["Town/Time"].step
+ const old = { ...current, version: 1, resources: { ...current.resources, "Town/Time": { tick: count } } }
+ const storage = memoryStorage(new Map([["inkline-town/save/manual", JSON.stringify({ format: SAVE_FORMAT, version: 9, slot: "manual", savedAt: 0, title: "old town", world: old })]]))
+ town.run(1)
+ const result = Effect.runSync(Effect.result(load("manual").pipe(
+ Effect.provideService(Storage, storage),
+ Effect.provideService(World, { snapshot: () => town.snapshot(), title: () => "town", restore: (value) => {
+ try { town.restore(value); return null } catch (error) { return String(error) }
+ } })
+ )))
+ assert.equal(result._tag, "Success")
+ if (result._tag === "Success") assert.equal(result.success.version, SAVE_VERSION)
+ assert.deepEqual(town.snapshot().resources["Town/Time"], { step: count, hz: 60, dt: 1 / 60 })
+ assert.equal(town.snapshot().version, 2)
+})
+
+test("the full town simulation repeats from fresh scripted input", () => {
+ const result = Determinism.check(({ hostClock }) => ({
+ runtime: headless({ size: "small", term: 45, land: "fair", seed: 7 }, { hostClock }).runtime,
+ schedules: { simulate }
+ }), { schedule: "simulate", frames: 120, hostClock: HostClock.test() })
+ assert.deepEqual(result, { ok: true, frames: 120 })
+})
diff --git a/test/endless.test.ts b/test/endless.test.ts
index 9228d27..b5b0d18 100644
--- a/test/endless.test.ts
+++ b/test/endless.test.ts
@@ -7,7 +7,7 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import { amounts, FACE_TICKS, goodIds, kinds, ranks, ticks, YEARS_PER_TERM } from "../src/content.ts"
+import { amounts, FACE_TICKS, goodIds, kinds, ranks, stepsOf, YEARS_PER_TERM } from "../src/content.ts"
import { canPlace, GridBuilder } from "../src/grid.ts"
import { goalsOf, nextRank, scoreOf } from "../src/rules/goals.ts"
import { headless, type Snapshot } from "../src/sim/headless.ts"
@@ -32,7 +32,7 @@ const market = (s: Snapshot) => {
"Town/Building": { kind: "market" },
"Town/Status": "idle",
"Town/Staff": { needed: 0, assigned: 0, apprentices: 0, nearby: 0 },
- "Town/Service": { service: "goods", interval: ticks(m.service!.seconds), cooldown: 0, range: m.service!.range },
+ "Town/Service": { service: "goods", interval: stepsOf(m.service!.seconds), cooldown: 0, range: m.service!.range },
"Town/Inventory": { stock: amounts({}), accepts: ["fish", "smoked", "bread", "cloth"], cap: m.holds!.cap }
}
})
@@ -118,7 +118,7 @@ test("a market is upgraded to a market hall once the town is a town, and not bef
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(hall.components["Town/Service"].interval, stepsOf(up.service!.seconds))
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."))
})
@@ -190,7 +190,7 @@ test("a long reign: five terms follow one another, each judged on its own, and t
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/Time"].step = s.resources["Town/Charter"].founded + f.began + term - 120
s.resources["Town/Treasury"].coins = 5000
})
t.run(3)
diff --git a/test/homes-edit.test.ts b/test/homes-edit.test.ts
index 0828757..3486b90 100644
--- a/test/homes-edit.test.ts
+++ b/test/homes-edit.test.ts
@@ -7,7 +7,7 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import { STEP_SECONDS } from "../src/content.ts"
+import { step } from "../src/content.ts"
import { headless } from "../src/sim/headless.ts"
test("a homes edit along a fresh road raises every cottage in one step, empty", () => {
@@ -17,7 +17,7 @@ test("a homes edit along a fresh road raises every cottage in one step, empty",
{ type: "roads", cells: Array.from({ length: 9 }, (_, i) => ({ x: 34 + i, y: 31 })) },
{ type: "homes", cells: homes }
)
- town.run(STEP_SECONDS)
+ town.run(step.dt)
const houses = town.snapshot().entities.filter((entity) => entity.components["Town/House"] !== undefined)
assert.deepEqual(
houses.map((entity) => ({ tile: entity.components["Town/Tile"], residents: entity.components["Town/House"].residents })),
diff --git a/test/model.test.ts b/test/model.test.ts
index 343304e..c2de1b2 100644
--- a/test/model.test.ts
+++ b/test/model.test.ts
@@ -150,7 +150,7 @@ const apply = (town: Headless, command: Command): string | null => {
const s = town.snapshot()
const charter = s.resources["Town/Charter"]
const began = s.resources["Town/Fate"].began
- town.run(Math.max(0, charter.founded + began + charter.term * 3600 - s.resources["Town/Time"].tick) / 60 + 2)
+ town.run(Math.max(0, charter.founded + began + charter.term * 3600 - s.resources["Town/Time"].step) / 60 + 2)
return null
}
case "Road": {
@@ -260,7 +260,7 @@ interface Memory {
}
const remember = (s: Snapshot): Memory => ({
- tick: s.resources["Town/Time"].tick,
+ tick: s.resources["Town/Time"].step,
state: s.resources["Town/Fate"].state,
met: s.resources["Town/Crown"].met,
missed: s.resources["Town/Crown"].missed,
diff --git a/test/same-step-edits.test.ts b/test/same-step-edits.test.ts
index 214ebfb..918d53b 100644
--- a/test/same-step-edits.test.ts
+++ b/test/same-step-edits.test.ts
@@ -7,7 +7,7 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import { STEP_SECONDS, type CharterValue } from "../src/content.ts"
+import { step, type CharterValue } from "../src/content.ts"
import { headless } from "../src/sim/headless.ts"
const charter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }
@@ -23,22 +23,22 @@ const at = (town: ReturnType<typeof headless>, cell: { readonly x: number; reado
test("a home placed and pulled down in the same step is gone", () => {
const town = headless(charter)
town.edit({ type: "roads", cells: roads }, { type: "homes", cells: [home] }, { type: "remove", cell: home })
- town.run(STEP_SECONDS)
+ town.run(step.dt)
assert.deepEqual(at(town, home), [])
// The cell is free again: a home can go there next step.
town.edit({ type: "homes", cells: [home] })
- town.run(STEP_SECONDS)
+ town.run(step.dt)
assert.equal(at(town, home).length, 1)
})
test("a new town founded in the same step as a placement keeps nothing of it", () => {
const fresh = headless(charter)
fresh.edit({ type: "newTown", charter })
- fresh.run(STEP_SECONDS)
+ fresh.run(step.dt)
const town = headless(charter)
town.edit({ type: "roads", cells: roads }, { type: "homes", cells: [home] }, { type: "newTown", charter })
- town.run(STEP_SECONDS)
+ town.run(step.dt)
assert.equal(town.snapshot().entities.length, fresh.snapshot().entities.length)
assert.deepEqual(at(town, home), at(fresh, home))
diff --git a/tools/balance/scenario.ts b/tools/balance/scenario.ts
index 3b8169b..2d701a0 100644
--- a/tools/balance/scenario.ts
+++ b/tools/balance/scenario.ts
@@ -61,7 +61,7 @@ export const fromSnapshot = (snapshot: Snapshot, name = "saved-town", rules: Rul
if (type) land.push({ tile, type, amount: c["Town/Rock"]?.amount ?? 1, growth: c["Town/Tree"]?.growth ?? c["Town/Field"]?.growth ?? 0 })
}
const charter = r["Town/Charter"]
- return { name, charter, tick: r["Town/Time"].tick - charter.founded, coins: r["Town/Treasury"].coins, approval: r["Town/Mood"].approval,
+ return { name, charter, tick: r["Town/Time"].step - charter.founded, coins: r["Town/Treasury"].coins, approval: r["Town/Mood"].approval,
policy: r["Town/Policy"], trade: { ...r["Town/Policy"], prices: r["Town/Market"].prices }, homes, buildings, roads, land, ruins, parks, mask: r["Town/Land"].mask }
}
diff --git a/tools/balance/verify/fixture.ts b/tools/balance/verify/fixture.ts
index 5760d12..08f1e9c 100644
--- a/tools/balance/verify/fixture.ts
+++ b/tools/balance/verify/fixture.ts
@@ -43,7 +43,7 @@ export const fixture = (scenario: Scenario, rules: Rules): Headless => {
add({ "Town/Tile": l.tile, ...component })
}
s.resources["Town/Land"] = { mask: scenario.mask ?? "1".repeat(GRID * GRID), cells: GRID * GRID }
- s.resources["Town/Time"] = { tick: scenario.tick + 1 }
+ s.resources["Town/Time"] = { step: scenario.tick + 1, hz: 60, dt: 1 / 60 }
s.resources["Town/Charter"] = { ...scenario.charter, founded: 1, winters: scenario.charter.winters ?? s.resources["Town/Charter"].winters }
s.resources["Town/Treasury"] = { coins: scenario.coins }
s.resources["Town/Mood"] = { ...s.resources["Town/Mood"], approval: scenario.approval }
diff --git a/vite.config.ts b/vite.config.ts
index 04c7704..f7186d2 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,6 +1,6 @@
import { defineConfig } from "vite"
-import * as ReplayVitePlugin from "@typeonce/bevy-ts-devtools/ReplayVitePlugin"
+import * as ReplayVitePlugin from "@typeonce/ritmo-devtools/ReplayVitePlugin"
import { sharesInDev } from "./src/server/dev.ts"