From 1de8925a16c66b51834dcfed533ea5a7020479c9 Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:17:16 +0300 Subject: [PATCH 1/9] Seed one reactor tier down on bonus maps; solve a player's setup from the CLI - A second seed with the top reactor one tier down, kept when it stabilizes higher. Gated to terrain-bonus anomalies, where it was measured to help; neutral on the base maps. - solve CLI: --code solves a pasted board with its own anomaly and Time Lab research, --tier holds a building below its last tier, --plan adds upgrade-plan steps. --attempts now reports worst, median and best. - The Time Lab has twelve researches: Chrono Seed (skip_city) sets the City level a timeline starts at, and changes no layout. --- docs/SOLVER.md | 29 ++- docs/game-logic.md | 7 +- packages/solver/CLAUDE.md | 10 +- packages/solver/bin/report.ts | 12 ++ packages/solver/bin/solve.ts | 170 ++++++++++++++++-- packages/solver/bin/worker.ts | 11 +- .../solver/fixtures/three_island_uneven.json | 5 - packages/solver/src/data/prestige.ts | 3 +- packages/solver/src/solver/placementSearch.ts | 76 ++++++-- packages/solver/src/solver/search/repair.ts | 20 ++- .../sidebar/PrestigeUpgrades.svelte | 2 +- 11 files changed, 287 insertions(+), 58 deletions(-) diff --git a/docs/SOLVER.md b/docs/SOLVER.md index 713d76f..2a67ae4 100644 --- a/docs/SOLVER.md +++ b/docs/SOLVER.md @@ -227,6 +227,18 @@ the unchanged search across three seeds, because `powerPerTile` orders a greedy later stages rewrite, so skewing it toward the coast mostly changes which tiles are claimed first. Don't re-attempt either without a wider measurement. +**What did pay is a second seed with the top reactor one tier down** (`TIER_STEP`, the ×1.25 every +reactor steps by), rewritten in the real roster's buildings and kept when it stabilizes higher — +the move an upgrade plan already makes with today's tiers, and how it was found: a player's plan +run beat their plain one. On their board (Tidal legacy plus research) that seed stabilizes at +15.39AD against 13.95AD and wins every attempt; over 48 attempts at 20s the median rose from +19.58–19.63AD to 19.69–19.74AD and the worst from 19.32–19.41AD to 19.42–19.53AD, the best +unchanged. On the shipped maps it wins the seed comparison on every main island and moves nothing at the end: +maps 3, 5–8 under both Tidal variants, 30 attempts each, medians within ±0.04AD in both directions; +under the base rules the same, and on the player's board with the anomaly off the runs were +identical. So it is gated to a terrain bonus, where it was measured to help, and costs one seed +construction there; a plan run already has its own second seed and skips it. + `role_isolation` is resolved in `simulateIsland`, the one place a whole layout is in hand. It copies the placement into `ctx.ratedLayout` — held by the island, not allocated per call — re-rates the affected role's tiles and reads every figure through that. Two details are load-bearing: the @@ -857,10 +869,10 @@ Import dialog to see the board. code writer all three paths go through and it always passes `blueprintRules`, so the app's preview rates a CLI layout the way the run did rather than under the reader's own timeline — a coast-hugging Tidal board would otherwise come back at roughly its baseline figure with nothing -saying why. The research table it writes is **empty rather than absent**, which is a different -claim and a true one: the CLI solves at full unlocks and no Time Lab, and there is no flag for one, -so "the author had no research" is exactly what it knows, where an absent section would mean "rules -unknown". `--anomaly` also tags the filename (`test_4_tidal_ascendancy.txt`) and every header names +saying why. The research table it writes is the run's: a `--code` board's own, otherwise **empty +rather than absent**, which is a different claim and a true one — a shipped map is solved with no +Time Lab, so "the author had no research" is exactly what it knows, where an absent section would +mean "rules unknown". `--anomaly` also tags the filename (`test_4_tidal_ascendancy.txt`) and every header names the timeline, because a `solves/` directory or a session scrollback holding three timelines is otherwise unreadable from the outside — the same argument `formatNumberForFilename` makes about the power figure. The tag is the full id, so a filename pastes straight back into the flag that @@ -869,7 +881,14 @@ matches the optional tail, since that regex is what finds the previous ids: a ta could not see would restart numbering at 1 and overwrite an untagged run. `--attempts` runs a batch session: N whole solves through a worker pool, with a leaderboard of -distinct layouts at the end. Ctrl-C stops it and still prints the report. +distinct layouts at the end and the worst, median and best of every attempt — the spread is what +tells two settings apart when both reach the same best. Ctrl-C stops it and still prints the report. + +Three flags reproduce a player's setup rather than a shipped one. `--code BLUEPRINT` solves a +pasted board, taking its anomaly (unless `--anomaly` is given) and its Time Lab research from the +code's rules section. `--tier ID=LEVEL` holds a building below its last tier, and `--plan +ID=LEVEL` adds an upgrade-plan step, in buying order and resolved by `resolveUpgradePlan` exactly +as the app does; both count levels from 1, like the app's tier buttons. Cores are spent on two axes and the flags pick which. A **run** farms its islands out to the pool, each with its own slice (`islandBudgetsS`) of the budget. When every island has a worker of its diff --git a/docs/game-logic.md b/docs/game-logic.md index bd6367b..c81a8e4 100755 --- a/docs/game-logic.md +++ b/docs/game-logic.md @@ -396,9 +396,10 @@ it and the code differ, what is written here is the code. ## Time Lab Research -Eleven researches exist; **three** of them change a building's figures, and the -other eight move research income, research time, Chronons, obstacle-removal -cost, energy sale price and building prices — all decided before a board is +Twelve researches exist; **three** of them change a building's figures, and the +other nine move research income, research time, Chronons, obstacle-removal +cost, energy sale price, building prices and the City level a timeline starts +at — all decided before a board is laid out, so none can change which layout is best. | research | scales | levels (×) | diff --git a/packages/solver/CLAUDE.md b/packages/solver/CLAUDE.md index c80f468..f188a38 100644 --- a/packages/solver/CLAUDE.md +++ b/packages/solver/CLAUDE.md @@ -11,11 +11,11 @@ The app-side half — how `layoutState`, `configState`, `AnomalySelector` and ### Time Lab research -`PRESTIGE_UPGRADES` (`data/prestige.ts`) carries **three** of the game's eleven +`PRESTIGE_UPGRADES` (`data/prestige.ts`) carries **three** of the game's twelve researches: Absolute Zero (cooler cooling), Infinite Grid (generator and wind -turbine stats) and Stellar Forge (reactor heat). The other eight move research -income, research time, chronons, obstacle-removal, energy sale price and -building prices — all +turbine stats) and Stellar Forge (reactor heat). The other nine move research +income, research time, chronons, obstacle-removal, energy sale price, +building prices and the City level a timeline starts at — all decided _before_ the solver is handed a board, so none can change which layout is best. The file names them so it is clear they were read and dismissed. @@ -423,7 +423,7 @@ CoolingPerSec` — it is what a cooler is worth and what the game shows for it, they are bought with Chronons, survive a Time Jump, and stack with whatever anomaly is running — **multiplicatively**, so a generator under Singularity Isolation with Infinite Grid maxed is rated x8. The extractor's record covers -all eleven Time Lab upgrades; the three a layout can see are **Stellar Forge** +all twelve Time Lab upgrades; the three a layout can see are **Stellar Forge** (every heat producer, so reactors), **Infinite Grid** (generators _and_ wind turbines), and **Absolute Zero** (every cooler), each ten levels of `BonusPercentage`. Absolute Zero and Infinite Grid share one curve, 0.1 to 1.0 diff --git a/packages/solver/bin/report.ts b/packages/solver/bin/report.ts index 2da501e..9691ea3 100644 --- a/packages/solver/bin/report.ts +++ b/packages/solver/bin/report.ts @@ -210,6 +210,18 @@ export function printSessionReport(report: SessionReport): void { if (rules) console.log(rules); console.log(rule); console.log(`Estimated max: ${formatNumberPair(report.estimatedMaxPower)}`); + // The spread, not only the best: the top layouts say what a session *can* + // find, and two settings that both reach the same best can still differ in + // how often they get there. + if (report.powers.length) { + const sorted = [...report.powers].sort((a, b) => a - b); + const median = sorted[Math.floor((sorted.length - 1) / 2)]; + console.log( + `Attempts: ${sorted.length} | worst ${formatNumberPair(sorted[0])}` + + ` | median ${formatNumberPair(median)}` + + ` | best ${formatNumberPair(sorted[sorted.length - 1])}`, + ); + } if (!report.top.length) { console.log("\nNo attempts completed.\n"); diff --git a/packages/solver/bin/solve.ts b/packages/solver/bin/solve.ts index 8d3fb7d..33577cf 100644 --- a/packages/solver/bin/solve.ts +++ b/packages/solver/bin/solve.ts @@ -32,8 +32,18 @@ import os from "node:os"; import path from "node:path"; import { ANOMALIES, DEFAULT_ANOMALY_ID } from "../src/data/anomalies"; -import { BUILDINGS, allUpgradesUnlocked } from "../src/data/buildings"; +import { + BUILDINGS, + allUpgradesUnlocked, + findBuilding, +} from "../src/data/buildings"; import { getEffectiveBuildings } from "../src/data/effectiveBuildings"; +import { + MAX_UPGRADE_STEPS, + resolveUpgradePlan, + type UpgradeStep, +} from "../src/data/upgradePlan"; +import { prestigeScales } from "../src/data/prestige"; import { blueprintKey, blueprintRules, @@ -138,6 +148,18 @@ function offsetSeed( return (seed + index * SEED_STRIDE) >>> 0; } +/** + * What the player holds beyond the unlocked tiers: Time Lab research and an + * upgrade plan. Carried as one value so each solve path takes one more + * argument rather than two. + */ +interface Progress { + /** Research levels, keyed and indexed like the player's own record. */ + research: Record; + /** The plan's rosters before its target, today's first — `resolveUpgradePlan`'s `along`. */ + upgradePlan: Record[]; +} + // --- Solving ------------------------------------------------------------- /** @@ -156,6 +178,7 @@ async function solveWithPool( timeBudgetS: number, seed: number | undefined, anomalyId: AnomalyId | undefined, + progress: Progress, pool: WorkerPool | null, ): Promise { const plan = planSolve( @@ -165,6 +188,8 @@ async function solveWithPool( timeBudgetS, seed, anomalyId, + prestigeScales(progress.research), + progress.upgradePlan, ); if (!plan || plan.islands.length < 2 || !pool || pool.size < 2) return solve( @@ -172,7 +197,11 @@ async function solveWithPool( [...BUILDINGS], unlockedUpgrades, timeBudgetS, - { anomalyId }, + { + anomalyId, + prestige: prestigeScales(progress.research), + upgradePlan: progress.upgradePlan, + }, seed, ); @@ -198,6 +227,7 @@ async function solveWithPool( // resolved it, and a worker re-resolving would be a second reading of // the same string. anomaly: plan.anomaly, + upgradeSteps: plan.upgradeSteps, }, })), (i, result) => { @@ -217,10 +247,10 @@ async function solveWithPool( * would come back at roughly its baseline figure with nothing on screen saying * why. * - * The research table is **empty rather than absent**, which is a truthful - * statement and not the same claim: the CLI solves at full building unlocks and - * no Time Lab (there is no flag for one), so "the author had no research" is - * exactly what it knows. `DEFAULT_ANOMALY_ID` spells the absence of `--anomaly` + * The research table is the one the run solved under — a `--code` board's own, + * otherwise **empty rather than absent**, which is a truthful statement and not + * the same claim: "the author had no research" is exactly what the CLI knows + * about a shipped map. `DEFAULT_ANOMALY_ID` spells the absence of `--anomaly` * for the same reason — "no anomaly" is a real choice, and stating it is what * keeps a reader off their own. */ @@ -228,12 +258,13 @@ async function codeFor( grid: Tile[][], result: OptimizationResult, anomalyId: AnomalyId | undefined, + research: Record, ): Promise { return encodeBlueprint( grid, result.placements, placementTiers(result.placements), - blueprintRules(anomalyId ?? DEFAULT_ANOMALY_ID, {}), + blueprintRules(anomalyId ?? DEFAULT_ANOMALY_ID, research), ); } @@ -264,10 +295,15 @@ async function solveMap( filenameFor: (run: SolveRun, bestPower: number) => string, seed: number | undefined, anomalyId: AnomalyId | undefined, + progress: Progress, pool: WorkerPool | null, ): Promise { const { grid } = await decodeBlueprint(gameMap.code); - const roster = getEffectiveBuildings(BUILDINGS, unlockedUpgrades); + const roster = getEffectiveBuildings( + BUILDINGS, + unlockedUpgrades, + prestigeScales(progress.research), + ); const results: SolveRun[] = []; for (let runNum = 1; runNum <= runs; runNum++) { @@ -279,13 +315,14 @@ async function solveMap( timeLimitS, offsetSeed(seed, runNum - 1), anomalyId, + progress, pool, ); results.push({ runNum, result, elapsedS: (Date.now() - started) / 1000, - code: await codeFor(grid, result, anomalyId), + code: await codeFor(grid, result, anomalyId, progress.research), }); } @@ -307,6 +344,7 @@ async function runSingle( timeLimitS: number, seed: number | undefined, anomalyId: AnomalyId | undefined, + progress: Progress, pool: WorkerPool | null, ): Promise { const testId = nextOutputId(TEST_FILENAME_RE); @@ -320,6 +358,7 @@ async function runSingle( () => filename, seed, anomalyId, + progress, pool, ); @@ -338,6 +377,7 @@ async function runComparison( timeLimitS: number, seed: number | undefined, anomalyId: AnomalyId | undefined, + progress: Progress, pool: WorkerPool | null, ): Promise { const sessionId = nextOutputId(ISLAND_FILENAME_RE); @@ -361,6 +401,7 @@ async function runComparison( filenameFor, seed, anomalyId, + progress, pool, ); @@ -382,10 +423,15 @@ function workerCount(attempts: number, requested?: number): number { async function runSession( gameMap: CliMap, unlockedUpgrades: Record, + progress: Progress, args: Args, ): Promise { const { grid } = await decodeBlueprint(gameMap.code); - const roster = getEffectiveBuildings(BUILDINGS, unlockedUpgrades); + const roster = getEffectiveBuildings( + BUILDINGS, + unlockedUpgrades, + prestigeScales(progress.research), + ); const attempts = args.attempts!; const inFlight = workerCount(attempts, args.workers); const board = new Leaderboard(args.top); @@ -429,6 +475,8 @@ async function runSession( timeLimitS: args.timeLimitS, seed: offsetSeed(args.seed, i), anomalyId: args.anomalyId, + prestige: prestigeScales(progress.research), + upgradePlan: progress.upgradePlan, }, })), (attempt, raw) => { @@ -447,7 +495,7 @@ async function runSession( power: result.totalPower, attempt, activeTiles: result.activeTilesCount, - code: await codeFor(grid, result, args.anomalyId), + code: await codeFor(grid, result, args.anomalyId, progress.research), key: blueprintKey(grid, result.placements), }; board.offer(candidate); @@ -472,10 +520,11 @@ async function runSession( async function runSessions( gameMaps: CliMap[], unlockedUpgrades: Record, + progress: Progress, args: Args, ): Promise { for (const gameMap of gameMaps) { - const report = await runSession(gameMap, unlockedUpgrades, args); + const report = await runSession(gameMap, unlockedUpgrades, progress, args); printSessionReport(report); // Ctrl-C stops the session it was pressed in; it does not mean "move on to // the next map", which on `--all` would be another half hour away. @@ -496,11 +545,18 @@ interface Args { workers: number | undefined; seed: number | undefined; anomalyId: AnomalyId | undefined; + /** Tiers held below the last, 0-based like `unlockedUpgrades`. */ + tiers: Record; + /** The upgrade plan, in buying order. */ + plan: UpgradeStep[]; + /** A pasted board to solve instead of a shipped map. */ + code: string | undefined; } const USAGE = `usage: solve [-h] [--map NUM] [--all] [--runs RUNS] [--time TIME_LIMIT_S] [--attempts N] [--top K] [--workers N] [--seed SEED] - [--anomaly ID] + [--anomaly ID] [--tier ID=LEVEL] [--plan ID=LEVEL] + [--code BLUEPRINT] Decode a map, solve it, and report on the result. @@ -522,6 +578,20 @@ options: One of: ${ANOMALIES.map((a) => a.id).join(", ")}. Only the rules the solver implements take effect; the rest are accepted and ignored, exactly as in the app. + --tier ID=LEVEL + hold a building below its last tier (repeatable). LEVEL counts + from 1, like the app's tier buttons; every building not named + is fully upgraded + --plan ID=LEVEL + one step of an upgrade plan (repeatable, in buying order, at + most ${MAX_UPGRADE_STEPS}): the run scores at the tiers after the last + step and keeps only layouts that also run at --tier's tiers + and after each step, exactly as the app's upgrade plan does + --code BLUEPRINT + solve a pasted board instead of a shipped map. Its rules + section, when it has one, supplies the anomaly (unless + --anomaly is given) and the Time Lab research; placements + on it are ignored This renders no picture. Each run writes its blueprint code to solves/, named after what it found and after the anomaly it found it under; paste one into the @@ -539,6 +609,9 @@ function parseArgs(argv: string[]): Args | null { workers: undefined, seed: undefined, anomalyId: undefined, + tiers: {}, + plan: [], + code: undefined, }; const takeValue = ( @@ -567,6 +640,20 @@ function parseArgs(argv: string[]): Args | null { return n; }; + // `ID=LEVEL`, with LEVEL 1-based as typed and 0-based as carried. + const asUpgradeStep = (flag: string, raw: string): UpgradeStep => { + const [buildingId, levelRaw] = raw.split("="); + const def = findBuilding(buildingId); + if (!def || levelRaw === undefined) + throw new Error(`argument ${flag}: expected ID=LEVEL, got '${raw}'`); + const level = asInt(flag, levelRaw); + if (level < 1 || level > def.levels.length) + throw new Error( + `argument ${flag}: ${buildingId} has levels 1-${def.levels.length}, got ${level}`, + ); + return { buildingId, level: level - 1 }; + }; + for (let i = 0; i < argv.length; i++) { const token = argv[i]; const eq = token.indexOf("="); @@ -627,6 +714,18 @@ function parseArgs(argv: string[]): Args | null { args.anomalyId = match.id; } break; + case "--code": + [raw, i] = takeValue(flag, inline, i); + args.code = raw; + break; + case "--tier": + case "--plan": { + [raw, i] = takeValue(flag, inline, i); + const step = asUpgradeStep(flag, raw); + if (flag === "--tier") args.tiers[step.buildingId] = step.level; + else args.plan.push(step); + break; + } default: throw new Error(`unrecognized arguments: ${token}`); } @@ -646,7 +745,21 @@ export async function main(argv: string[]): Promise { if (!args) return 0; let selected: CliMap[]; - if (args.all) { + let research: Record = {}; + if (args.code !== undefined) { + let rules; + try { + ({ rules } = await decodeBlueprint(args.code)); + } catch (err) { + console.error(`--code: ${(err as Error).message}`); + return 1; + } + selected = [{ num: -1, name: "pasted board", code: args.code }]; + if (rules) { + research = rules.research; + args.anomalyId ??= ANOMALIES.find((a) => a.id === rules.anomalyId)?.id; + } + } else if (args.all) { selected = MAPS; } else if (args.maps.length) { const unknown = args.maps.filter((n) => !MAPS_BY_NUM.has(n)); @@ -661,7 +774,30 @@ export async function main(argv: string[]): Promise { selected = [MAPS_BY_NUM.get(DEFAULT_MAP_NUM)!]; } - const unlockedUpgrades = allUpgradesUnlocked(); + if (args.plan.length > MAX_UPGRADE_STEPS) { + console.error(`--plan takes at most ${MAX_UPGRADE_STEPS} steps`); + return 1; + } + const { target: unlockedUpgrades, along: upgradePlan } = resolveUpgradePlan( + BUILDINGS, + { ...allUpgradesUnlocked(), ...args.tiers }, + args.plan, + ); + if (args.plan.length && upgradePlan.length === 0) { + console.error("--plan raises nothing: no step is above its --tier"); + return 1; + } + const progress: Progress = { research, upgradePlan }; + if (Object.keys(research).length) + console.log( + `Research: ${Object.entries(research) + .map(([id, level]) => `${id} ${level + 1}`) + .join(", ")}`, + ); + if (upgradePlan.length) + console.log( + `Upgrade plan: ${args.plan.map((s) => `${s.buildingId} -> ${s.level + 1}`).join(", ")}\n`, + ); if (args.attempts !== undefined) { if (args.attempts < 1) { @@ -672,7 +808,7 @@ export async function main(argv: string[]): Promise { console.error("--workers must be at least 1"); return 1; } - return runSessions(selected, unlockedUpgrades, args); + return runSessions(selected, unlockedUpgrades, progress, args); } const pool = new WorkerPool(WORKER_URL, os.cpus().length); @@ -685,6 +821,7 @@ export async function main(argv: string[]): Promise { args.timeLimitS, args.seed, args.anomalyId, + progress, pool, ); else @@ -694,6 +831,7 @@ export async function main(argv: string[]): Promise { args.timeLimitS, args.seed, args.anomalyId, + progress, pool, ); } finally { diff --git a/packages/solver/bin/worker.ts b/packages/solver/bin/worker.ts index d3cf692..dbb87dd 100644 --- a/packages/solver/bin/worker.ts +++ b/packages/solver/bin/worker.ts @@ -17,6 +17,7 @@ import type { AnomalyId, EffectiveBuilding, IslandSubGrid, + PrestigeScales, Tile, } from "../src/solver/types"; @@ -28,6 +29,7 @@ type Task = budgetS: number; seed?: number; anomaly?: AnomalyDefinition; + upgradeSteps?: EffectiveBuilding[][]; } | { kind: "attempt"; @@ -36,6 +38,8 @@ type Task = timeLimitS: number; seed?: number; anomalyId?: AnomalyId; + prestige?: PrestigeScales; + upgradePlan?: Record[]; }; parentPort?.on( @@ -51,13 +55,18 @@ parentPort?.on( undefined, payload.seed, payload.anomaly, + payload.upgradeSteps, ) : await solve( payload.grid, [...BUILDINGS], payload.unlockedUpgrades, payload.timeLimitS, - { anomalyId: payload.anomalyId }, + { + anomalyId: payload.anomalyId, + prestige: payload.prestige, + upgradePlan: payload.upgradePlan, + }, payload.seed, ); parentPort?.postMessage({ meta, result }); diff --git a/packages/solver/fixtures/three_island_uneven.json b/packages/solver/fixtures/three_island_uneven.json index 8083490..5bf834b 100755 --- a/packages/solver/fixtures/three_island_uneven.json +++ b/packages/solver/fixtures/three_island_uneven.json @@ -94,11 +94,6 @@ "y": 0, "building_id": "cooler8" }, - { - "x": 12, - "y": 0, - "building_id": "wind_turbine" - }, { "x": 0, "y": 1, diff --git a/packages/solver/src/data/prestige.ts b/packages/solver/src/data/prestige.ts index 51b1b87..3ffc779 100644 --- a/packages/solver/src/data/prestige.ts +++ b/packages/solver/src/data/prestige.ts @@ -14,7 +14,7 @@ import type { * carries a `multiplier` array that is just `1 + values`, and it is not copied, * because deriving it is what keeps the two from drifting. * - * **Three of the game's eleven are here.** The other eight change the economy + * **Three of the game's twelve are here.** The other nine change the economy * around the board rather than anything on it, and the solver cannot feel any * of them — they are listed so it is clear they were read and dismissed rather * than missed: @@ -25,6 +25,7 @@ import type { * - `erased_from_time` / `phase_breaker` — obstacle removal time and cost * - `quantum_exchange` — energy sale price * - `quantum_replicator` — building prices + * - `skip_city` (Chrono Seed) — the City level the next timeline starts at * - `zero_time_protocol` — free research speed-up window * * The solver optimises power on a fixed board from a fixed roster. What a diff --git a/packages/solver/src/solver/placementSearch.ts b/packages/solver/src/solver/placementSearch.ts index 22395d3..3e57fd2 100755 --- a/packages/solver/src/solver/placementSearch.ts +++ b/packages/solver/src/solver/placementSearch.ts @@ -9,6 +9,7 @@ import type { IslandLayout, IslandSubGrid, PlacedBuilding, + Placement, SearchHooks, } from "./types"; import { hillClimb } from "./search/anneal"; @@ -304,6 +305,13 @@ export async function replayIslandDeterministic( }; } +/** + * How much one reactor tier is worth over the one below it. Every reactor in + * the catalogue steps by this factor, give or take the authored rounding, so + * dividing by it is "one tier down" without a second lookup into the table. + */ +const TIER_STEP = 1.25; + /** * Solves one island. * @@ -313,7 +321,6 @@ export async function replayIslandDeterministic( * narrows run-to-run variance rather than eliminating it. Omitting it draws a * fresh seed, preserving the stochastic default. */ - export async function solveIsland( island: IslandSubGrid, effectiveBuildings: EffectiveBuilding[], @@ -387,12 +394,32 @@ export async function solveIsland( deadlineMs, ); + // A seed built from a roster other than the one being scored, rewritten in + // the scored roster's buildings by id, replaces the seed when it runs better. + const targetById = new Map(effectiveBuildings.map((b) => [b.id, b])); + const adoptIfBetter = (altSeed: Placement) => { + const remapped = emptyPlacement(ctx.n); + for (let t = 0; t < ctx.n; t++) { + const b = altSeed[t]; + const target = b === null ? undefined : targetById.get(b.id); + if (target !== undefined) put(remapped, ctx, t, target); + } + if (stabilize(remapped, ctx).power > stabilize(seed, ctx).power) { + seed = remapped; + } + }; + // Under a plan, a seed built from the target roster is sized for buildings // the player does not have yet: fewer coolers than today's tiers need, so // stabilizing it strips it bare — and nothing downstream puts the cooling // back, since a cooler that only today needs never raises target power. So // seed from the first step (today's tiers) as well, written in target // buildings, and start from whichever runs better across the plan. + // + // Under a terrain bonus without a plan, seed as well from the roster with + // its top reactor one tier down: the shore multiplies a hub's heat, so a + // seed sized for the full reactor is short of cooling there, the same way a + // target-sized seed is under a plan. See `docs/SOLVER.md`. const plan = upgradePlans.get(ctx); if (plan !== undefined) { const today = plan.steps[0]; @@ -401,24 +428,37 @@ export async function solveIsland( .filter((b) => b.type === type) .map(pool) .sort((a, b) => b[key] - a[key]); - const todaySeed = constructMultiStartSeed( - ctx, - byRole("reactor", "effectiveValue"), - byRole("generator", "effectiveValue"), - byRole("cooler", "effectiveValue"), - byRole("direct_producer", "energy"), - deadlineMs, + adoptIfBetter( + constructMultiStartSeed( + ctx, + byRole("reactor", "effectiveValue"), + byRole("generator", "effectiveValue"), + byRole("cooler", "effectiveValue"), + byRole("direct_producer", "energy"), + deadlineMs, + ), + ); + } else if ( + ctx.anomaly.rule === "terrain_affinity" && + !ctx.uniformRating && + reactors.length > 0 + ) { + const top = reactors[0]; + const weaker = reactors + .map((b) => + b === top ? { ...b, effectiveValue: b.effectiveValue / TIER_STEP } : b, + ) + .sort((a, b) => b.effectiveValue - a.effectiveValue); + adoptIfBetter( + constructMultiStartSeed( + ctx, + weaker, + generators, + coolers, + directProducers, + deadlineMs, + ), ); - const targetById = new Map(effectiveBuildings.map((b) => [b.id, b])); - const remapped = emptyPlacement(ctx.n); - for (let t = 0; t < ctx.n; t++) { - const b = todaySeed[t]; - const target = b === null ? undefined : targetById.get(b.id); - if (target !== undefined) put(remapped, ctx, t, target); - } - if (stabilize(remapped, ctx).power > stabilize(seed, ctx).power) { - seed = remapped; - } } // Repair the seed before annealing, and again afterwards. Seed construction diff --git a/packages/solver/src/solver/search/repair.ts b/packages/solver/src/solver/search/repair.ts index 4dbeda3..d16731f 100644 --- a/packages/solver/src/solver/search/repair.ts +++ b/packages/solver/src/solver/search/repair.ts @@ -188,7 +188,8 @@ export async function greedyPolish( * Post-search cleanup: * 1. Drops every producer generating 0 power, repeating until none remain. * 2. Sequentially tests removing reactors/coolers to eliminate redundant - * support structures. + * support structures, and direct producers whose output the island's + * total is too large to register. * 3. Guarantees a stable layout — every returned producer is online — with a * minimal active tile footprint. * @@ -215,12 +216,25 @@ export function pruneDeadWeight( let bestPower = stabilized.power; let rows = stabilized.rows; - // 2. Greedy backward sweep: test removing support buildings (reactors & coolers). + // 2. Greedy backward sweep: test removing support buildings (reactors & + // coolers), and direct producers too. + // + // A direct producer earns its tile on a small island, where a wind turbine + // beside a cooler is the most two tiles can make. On a large one its output + // is below the resolution of the island's total: 7 added to 1.5e25 is + // 1.5e25 exactly, since a double's last place there is around 2e9. Every + // comparison the search makes then reads it as worth nothing, so the walk + // drifts turbines in as neutral moves (a zero delta is always accepted) and + // nothing ever has a reason to take them out. Measured on Shadowspire under + // Singularity: five turbines across its two main islands on one run, none on + // the next. Removing one is accepted on the same guard as any support + // building — total power not lower — so a turbine whose 7 registers stays. const support: number[] = []; for (let tile = 0; tile < ctx.n; tile++) { const b = current[tile]; if (b === null) continue; - if (b.type === "cooler" || isReactor(b)) support.push(tile); + if (b.type === "cooler" || b.type === "direct_producer" || isReactor(b)) + support.push(tile); } for (const tile of support) { diff --git a/src/lib/components/sidebar/PrestigeUpgrades.svelte b/src/lib/components/sidebar/PrestigeUpgrades.svelte index eaf6b26..7ac5101 100644 --- a/src/lib/components/sidebar/PrestigeUpgrades.svelte +++ b/src/lib/components/sidebar/PrestigeUpgrades.svelte @@ -7,7 +7,7 @@ * The Time Lab research that changes what buildings are worth. * * Only the three the solver can feel are listed — `PRESTIGE_UPGRADES` says - * which of the game's eleven those are and why the other eight are not: the + * which of the game's twelve those are and why the other nine are not: the * rest change the economy around the board rather than anything on it. * * **Toggled and levelled exactly like a building**, down to the edge stripe From 39c78cd86714307d969cb7297d302d80dedc8e5b Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:17:16 +0300 Subject: [PATCH 2/9] Read the game export's timeline section Game 1.1.11 appends section 7 to the Export to Optimizer code: export time, Chronon balance, timeline energy and elapsed time, the game's own jump award, the anomalies whose first-entry bonus is spent and the generation, then the signed cash balance (negative on build credit), research points, and a byte saying whether "Exported at" is server time or the device clock. Codes from before it read with timeline: null, and a section that ends early reads the later fields as null. The fixtures are the developer's 1.1.11 samples, ending with the clock byte, with server-stamped copies of three saves; owner_editor_save is the one real code that ends at research points. Two are a player's save. One sample has buildings on the transformer cells of areas 6-8, which the import drops; the test pins it. The spec records what the samples measured and the drift the game's developer found: its ticks run about 0.3% slow while it is open, so a projection on the real clock leads the game by that much of its online time. That is the game's to fix and is not modelled. --- docs/game-export.md | 80 +++++++- packages/solver/src/encoding/gameExport.ts | 118 +++++++++++ packages/solver/tests/gameExport.test.ts | 190 +++++++++++++++++- .../tests/gameExports/editor_current_save.txt | 1 + .../tests/gameExports/gen0_none_city2.txt | 1 + .../gameExports/gen0_none_city2_server.txt | 1 + .../tests/gameExports/gen1_cryo_city41.txt | 1 + .../gameExports/gen1_singularity_city50.txt | 1 + .../gameExports/gen2_city52_9c43e4b7.txt | 1 + .../gen2_city52_9c43e4b7_server.txt | 1 + .../tests/gameExports/gen2_cryo_city34.txt | 1 + .../gameExports/gen2_singularity_city32.txt | 1 + .../tests/gameExports/gen3_tidal_city31.txt | 1 + .../tests/gameExports/gen6_tidal_city49.txt | 1 + .../gameExports/gen6_tidal_city49_server.txt | 1 + .../tests/gameExports/owner_editor_save.txt | 1 + 16 files changed, 396 insertions(+), 5 deletions(-) create mode 100644 packages/solver/tests/gameExports/editor_current_save.txt create mode 100644 packages/solver/tests/gameExports/gen0_none_city2.txt create mode 100644 packages/solver/tests/gameExports/gen0_none_city2_server.txt create mode 100644 packages/solver/tests/gameExports/gen1_cryo_city41.txt create mode 100644 packages/solver/tests/gameExports/gen1_singularity_city50.txt create mode 100644 packages/solver/tests/gameExports/gen2_city52_9c43e4b7.txt create mode 100644 packages/solver/tests/gameExports/gen2_city52_9c43e4b7_server.txt create mode 100644 packages/solver/tests/gameExports/gen2_cryo_city34.txt create mode 100644 packages/solver/tests/gameExports/gen2_singularity_city32.txt create mode 100644 packages/solver/tests/gameExports/gen3_tidal_city31.txt create mode 100644 packages/solver/tests/gameExports/gen6_tidal_city49.txt create mode 100644 packages/solver/tests/gameExports/gen6_tidal_city49_server.txt create mode 100644 packages/solver/tests/gameExports/owner_editor_save.txt diff --git a/docs/game-export.md b/docs/game-export.md index 065224a..eba2e5c 100644 --- a/docs/game-export.md +++ b/docs/game-export.md @@ -128,9 +128,12 @@ Primitive encodings (what .NET's `BinaryWriter` writes, UTF-8): | `int16` | 2, little-endian, signed | | `uint16` | 2, little-endian | | `int32` | 4, little-endian, signed | +| `int64` | 8, little-endian, signed | +| `double` | 8, IEEE 754, little-endian | | `string` | 7-bit-encoded length (LEB128), then that many UTF-8 bytes | -Six sections, always present, always in this order: +Seven sections, always present, always in this order (section 7 since game +1.1.11; an older code ends after section 6): | # | Section | Contents | | --- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------- | @@ -140,6 +143,7 @@ Six sections, always present, always in this order: | 4 | Research | `uint16` count · per `ResearchSO`, all domains: `string` research id · `uint16` level | | 5 | Research in progress | `uint16` count · per entry: `string` research id · `uint16` level it will reach · `int32` seconds left | | 6 | Obstacles being cleared | `uint16` count · per entry: `int16` x · `int16` y · `int32` seconds left | +| 7 | Timeline | see 4.5 | Rules: @@ -197,6 +201,46 @@ y = minY + 1 : grass cooler2 generator7 has the cell bytes `00 01 02 01 07 08`. +### 4.5 Timeline + +Where the player's timeline stands, for the optimizer's Chronon tools. In this +order: + +| Field | Type | Meaning | +| ------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| Exported at | `int64` | Moment of export, Unix seconds, UTC: server time once the game has synced, the device clock otherwise | +| Chronon balance | `int64` | Chronons held, unspent | +| Timeline energy | `double` | `TimelineEnergyProduced`, online + offline: the `E` of the award | +| Timeline elapsed | `int64` | Seconds since the timeline began, on the game's internal clock | +| Jump award now | `int64` | The game's own award for a jump now, **without** the first-entry bonus; 0 at zero energy | +| Anomalies entered | `uint16` count · count × `string` | Anomalies whose first-entry bonus is spent. Always `tidal_ascendancy`, never `tidal_ascendancy_legacy`: the bonus belongs to the anomaly | +| Timeline generation | `int32` | Time Jumps completed, 0 before the first | +| Cash | `double` | The raw signed balance: negative while building on credit | +| Research points | `double` | Research points held | +| Stamp source | `byte` | Which clock wrote "Exported at": 0 server time, 1 the device clock (the game had not synced) | + +Cash and research points were appended after the first samples, and the stamp +source after them, so a code that ends at any of those fields is a valid, older +section 7. Cash goes **below zero** on +build credit: a purchase is allowed while `cash − cost ≥ −limit`, the limit set by +the Build Credit research in section 4. The caps on both balances also come from +research, and are multiplied while Rush Hour runs. + +The award, as the developer gave it: + +``` +Chronons = max(1, floor(97.34 × (E / 2.82e16)^0.135 × M)) + B +``` + +`M` is the Chronon Reactor multiplier (its level is in section 4), `B` is 88 +on the first entry into an anomaly and 0 otherwise. A jump is allowed once the +award without `B` reaches `min(5000, round(88 × 1.15^generation))`, midpoint +rounded away from zero. + +For a save older than the Time Jump feature that has not jumped yet, timeline +energy and elapsed are counted from its first launch after that update; the +two still agree, so energy per second is right. + ## 5. Versioning - The format version is the digit in the `R2X1.` prefix. @@ -235,6 +279,40 @@ first three real exports came to 2,347–2,460 characters. The roster also lists `research_building_tidal_plant`, a building the optimizer does not carry yet. The reader matches ids exactly and skips unknown ones. +- **The 1.1.11 timeline samples** are in `tests/gameExports/` as + `gen__city.txt`, the third round, ending with the + clock byte. A `_server` file is the same save stamped by server time (the + editor's sync fed from an NTP clock), the rest by the device clock. + `owner_editor_save` is kept from the second round as the one real code that + ends at research points. Each one's jump award matches the formula in 4.5. + One of them, `gen1_cryo_city41`, has a building on the transformer cell of + areas 6, 7 and 8; the importer drops those three. +- **The power is right to under 100 parts per million.** `gen2_city52_9c43e4b7` + is a player's save, exported repeatedly with the same boards. The energy the + game added between two exports, over the time between, is its real rate, and + the simulator's power for those boards, as energy per 3-second tick, lands + within 25–66 ppm of it whenever the gap was offline. `editor_current_save`, + the same save after some play in the editor, comes out 229 ppm slower: the + online tick drift below, measured. +- **An editor export runs about 10 s ahead.** On that same save the projected + next Chronon arrived 10–11 s before the game's, with the browser's clock + correct. The code came from the developer's Unity editor, which loaded the + save and credited its offline income by its own game clock — and the game's + anti-tampering can hold that clock off real time. So the editor's copy was 10 + s ahead of the player's phone, and the projection was right for the copy it + was given. A player's own export has energy and stamp from one copy, so the + stamp should stay **server time**: that is the real moment the energy + describes, where a game-clock stamp would carry the anti-tampering offset into + every projection. The weak spot is the unsynced fallback to the device clock. +- **The game runs slow while it is open (a game bug, being fixed).** Its + production tick waits 3 s after the previous one and the wait ends on the next + frame, so each tick runs a few milliseconds long: about 0.3% slow at 60 fps + (~10 s an hour), 0.5% at 30 fps, and more on frame hitches. Offline time is + counted in real time. So a projection on the real clock pulls ahead of the game + by that fraction of the time it has been open since the export — the + projection is right and the game drifts. The developer also suspects a short + focus loss credits the gap since the last autosave (every 15 s) rather than + since the pause. Neither is modelled here: both are the game's to fix. - **A code can pick up stray characters when pasted.** One sample ended in a stray `ś`. The reader drops anything outside the base64url alphabet before decoding; a code damaged in the middle still fails, at the inflate. diff --git a/packages/solver/src/encoding/gameExport.ts b/packages/solver/src/encoding/gameExport.ts index a2d8c16..d901047 100644 --- a/packages/solver/src/encoding/gameExport.ts +++ b/packages/solver/src/encoding/gameExport.ts @@ -29,11 +29,23 @@ import { base64UrlToUint8Array, pipeThrough } from "./streams"; * 4. research uint16 n · n × (string id · uint16 level) * 5. ongoing uint16 n · n × (string id · uint16 target level · int32 secs) * 6. clearing uint16 n · n × (int16 x · int16 y · int32 secs) + * 7. timeline int64 exported at (Unix s, UTC) · int64 chronons · double + * timeline energy · int64 timeline secs · int64 award now · + * uint16 n · n × string anomaly entered · int32 generation + * [· double cash · double research points + * [· byte stamp source: 0 server, 1 device clock]] * * Integers are little-endian; a string is a 7-bit-encoded length followed by * UTF-8. A section appended after these is ignored rather than refused, so the * game can grow the format without a version bump; anything else is a new * version, and an unknown version is refused rather than guessed at. + * + * Section 7 arrived that way, in game 1.1.11, so a code written before it ends + * after section 6 and reads with `timeline: null`. It is all-or-nothing up to + * the generation: a code that starts it must finish it, since a half-read + * timeline would hand the Chronon figures a stray number. Cash and research + * points were appended after the first samples, by the same rule, so a code + * ending at the generation reads them as null. */ /** The only format version this build reads. */ @@ -71,6 +83,56 @@ export interface GameExportClearing { secondsLeft: number; } +/** + * Where the player's timeline stands at the moment of export — the figures a + * Time Jump is paid from. See `docs/game-export.md` section 4.5. + */ +export interface GameExportTimeline { + /** + * Unix seconds, UTC: the game's server time when it has synced, the device + * clock otherwise. What a code pasted later is brought forward from. + */ + exportedAt: number; + /** Chronons held, unspent. */ + chronons: number; + /** + * `TimelineEnergyProduced`, online and offline — the `E` the award is + * computed from. A save older than the Time Jump counts from its first + * launch after that update, and so does `elapsedSeconds`. + */ + energy: number; + /** Seconds since the timeline began, on the game's own clock. */ + elapsedSeconds: number; + /** + * The game's own award for jumping now, **without** the first-entry bonus: + * that one depends on which anomaly the jump picks. + */ + jumpAward: number; + /** + * Anomalies whose first-entry bonus is spent. Tidal Ascendancy is always + * `tidal_ascendancy` here, whatever balance the header names — the bonus + * belongs to the anomaly, not to its balance. + */ + anomaliesEntered: string[]; + /** Time Jumps completed: 0 before the first. */ + generation: number; + /** + * The raw signed cash balance — **negative** while the player builds on + * credit, down to the limit Build Credit research sets. Null on a code from + * before the field. + */ + cash: number | null; + /** Research points held; null on a code from before the field. */ + researchPoints: number | null; + /** + * Which clock wrote `exportedAt`: the game's server time, or — when the game + * had not synced yet — the device's own, which may be off by however far the + * device is. Null on a code from before the field, or a value this build + * does not know. + */ + stampSource: "server" | "device" | null; +} + export interface GameExport { version: number; gameVersion: string; @@ -84,6 +146,8 @@ export interface GameExport { research: Record; researchInProgress: GameExportProgress[]; clearing: GameExportClearing[]; + /** Section 7, or null on a code the game wrote before it had one. */ + timeline: GameExportTimeline | null; } /** @@ -138,6 +202,29 @@ class Reader { return v; } + /** + * `BinaryWriter.Write(long)`, as a number. Every int64 in the format is a + * count or a time far inside 2^53, so nothing is lost by not being a bigint. + */ + i64(): number { + this.#need(8); + const low = this.#view.getUint32(this.#at, true); + const high = this.#view.getInt32(this.#at + 4, true); + this.#at += 8; + return high * 2 ** 32 + low; + } + + f64(): number { + this.#need(8); + const v = this.#view.getFloat64(this.#at, true); + this.#at += 8; + return v; + } + + get done(): boolean { + return this.#at >= this.#bytes.length; + } + /** `BinaryWriter.Write(string)`: a 7-bit-encoded length, then UTF-8. */ str(): string { let length = 0; @@ -243,6 +330,36 @@ export async function decodeGameExport(text: string): Promise { clearing.push({ x: r.i16(), y: r.i16(), secondsLeft: r.i32() }); } + let timeline: GameExportTimeline | null = null; + if (!r.done) { + const exportedAt = r.i64(); + const chronons = r.i64(); + const energy = r.f64(); + const elapsedSeconds = r.i64(); + const jumpAward = r.i64(); + const anomaliesEntered: string[] = []; + for (let n = r.u16(); n > 0; n--) anomaliesEntered.push(r.str()); + const generation = r.i32(); + const hasBalances = !r.done; + const cash = hasBalances ? r.f64() : null; + const researchPoints = hasBalances ? r.f64() : null; + const source = r.done ? null : r.u8(); + const stampSource = + source === 0 ? "server" : source === 1 ? "device" : null; + timeline = { + exportedAt, + chronons, + energy, + elapsedSeconds, + jumpAward, + anomaliesEntered, + generation, + cash, + researchPoints, + stampSource, + }; + } + return { version, gameVersion, @@ -253,5 +370,6 @@ export async function decodeGameExport(text: string): Promise { research, researchInProgress, clearing, + timeline, }; } diff --git a/packages/solver/tests/gameExport.test.ts b/packages/solver/tests/gameExport.test.ts index 0cd9187..d5eaa6e 100644 --- a/packages/solver/tests/gameExport.test.ts +++ b/packages/solver/tests/gameExport.test.ts @@ -6,11 +6,13 @@ * three saves: city level 23 in a first timeline (five islands, early * buildings, most obstacles still standing), city level 34 in a third timeline * (Cryo Nexus, Time Lab research, two islands still locked) and city level 47 - * in a first timeline (everything unlocked, one research running). They are the only evidence of what the game + * in a first timeline (everything unlocked, one research running). They + * predate section 7; the `gen*` samples beside them carry it, and have their + * own block at the end. They are the only evidence of what the game * actually writes, which is why most of what is pinned here is pinned against * them rather than against codes built in the test. */ -import { readFileSync } from "node:fs"; +import { readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { deflateRawSync } from "node:zlib"; @@ -53,6 +55,18 @@ class Writer { this.bytes.push(...b); return this; } + i64(v: number) { + const b = Buffer.alloc(8); + b.writeBigInt64LE(BigInt(v)); + this.bytes.push(...b); + return this; + } + f64(v: number) { + const b = Buffer.alloc(8); + b.writeDoubleLE(v); + this.bytes.push(...b); + return this; + } str(s: string) { const utf8 = Buffer.from(s, "utf8"); let n = utf8.length; @@ -165,8 +179,12 @@ describe("decodeGameExport", () => { await expect(decodeGameExport(city34.slice(0, 1200))).rejects.toThrow(); }); - it("ignores a section appended after the six it knows", async () => { - const w = tinyExport().str("a later section"); + it("ignores a section appended after the seven it knows", async () => { + const w = timelineSection(tinyExport()) + .f64(1e6) + .f64(5e4) + .u8(0) + .str("a later section"); const exp = await decodeGameExport(w.code()); expect(exp.islands[0]).toMatchObject({ areaId: "area_1", @@ -174,6 +192,170 @@ describe("decodeGameExport", () => { minY: 4, cells: ["TileGrass", "TileWater"], }); + expect(exp.timeline).toMatchObject({ + generation: 3, + cash: 1e6, + researchPoints: 5e4, + stampSource: "server", + }); + }); +}); + +/** + * The worked example of `docs/game-export.md`'s section 7, plus the generation + * field the game added after it. + */ +function timelineSection(w: Writer): Writer { + return w + .i64(1792540800) + .i64(6200) + .f64(5.14e29) + .i64(2592000) + .i64(6905) + .u16(1) + .str("cryo_nexus") + .i32(3); +} + +/** + * Section 7, the timeline. Saves the developer exported from 1.1.11 for this + * purpose, named `gen__city`; `gen2_city52_9c43e4b7` + * and `editor_current_save` are a player's, and a `_server` file is the same + * save stamped by server time rather than the device clock. They are the third + * round, which ends with the clock byte — except `owner_editor_save`, kept + * from the second, the one real code that ends at research points. Only the + * figures are pinned here — the award is the game's own, and whether our + * formula agrees with it is the Chronon module's to test. + */ +const TIMELINE_SAMPLES = readdirSync(DIR) + .filter((f) => !f.startsWith("city")) + .map((f) => f.replace(/\.txt$/, "")); +describe("the timeline section", () => { + const sample = (name: string) => + decodeGameExport(readFileSync(join(DIR, `${name}.txt`), "utf8")); + + it("is null on a code written before it existed", async () => { + for (const code of [city23, city34, city47]) { + expect((await decodeGameExport(code)).timeline).toBeNull(); + } + }); + + it("reads every figure the game wrote", async () => { + const exp = await sample("gen1_cryo_city41"); + expect(exp.gameVersion).toBe("1.1.11"); + expect(exp.timeline).toEqual({ + exportedAt: 1792610302, + chronons: 553, + energy: 8.906078559870158e25, + elapsedSeconds: 1841407, + jumpAward: 2051, + anomaliesEntered: ["cryo_nexus"], + generation: 1, + cash: 3.001636196701361e30, + researchPoints: 7630000001250, + stampSource: "device", + }); + }); + + it("reads a player who has never entered an anomaly", async () => { + const { timeline } = await sample("gen0_none_city2"); + expect(timeline).toMatchObject({ + energy: 23814, + jumpAward: 2, + anomaliesEntered: [], + generation: 0, + cash: 13926.60626791145, + researchPoints: 0, + }); + }); + + it("names Tidal Ascendancy plainly when the header names its legacy balance", async () => { + const exp = await sample("gen6_tidal_city49"); + expect(exp.anomalyId).toBe("tidal_ascendancy_legacy"); + expect(exp.timeline?.anomaliesEntered).toEqual([ + "cryo_nexus", + "singularity_isolation", + "tidal_ascendancy", + ]); + expect(exp.timeline?.generation).toBe(6); + }); + + /* + * One sample is not clean, and it is the game's save rather than our map: + * `gen1_cryo_city41` has a building standing on the transformer cell of + * areas 6, 7 and 8 (a chaos core, a psionic tower, a cooler6), where every + * other export writes `CantBuildHere`. The import drops each one and counts + * it, which is the rule — pinned so a fourth would show. + */ + const ON_TRANSFORMER: Record> = { + gen1_cryo_city41: { island6: 1, island7: 1, island8: 1 }, + }; + + it("reads every sample, and every one resolves onto our maps", async () => { + expect(TIMELINE_SAMPLES.length).toBe(13); + for (const name of TIMELINE_SAMPLES) { + const exp = await sample(name); + expect(exp.timeline, name).not.toBeNull(); + const r = await resolveGameExport(exp); + for (const island of r.islands) { + expect(island.blockedBuildings, `${name} ${island.templateId}`).toBe( + ON_TRANSFORMER[name]?.[island.templateId] ?? 0, + ); + } + } + }); + + it("reads the spec's worked example byte for byte", async () => { + const exp = await decodeGameExport(timelineSection(tinyExport()).code()); + expect(exp.timeline).toEqual({ + exportedAt: 1792540800, + chronons: 6200, + energy: 5.14e29, + elapsedSeconds: 2592000, + jumpAward: 6905, + anomaliesEntered: ["cryo_nexus"], + generation: 3, + cash: null, + researchPoints: null, + stampSource: null, + }); + }); + + it("reads cash and research points after the generation, debt included", async () => { + const w = timelineSection(tinyExport()).f64(-2.5e30).f64(9.15e11); + const { timeline } = await decodeGameExport(w.code()); + expect(timeline).toMatchObject({ cash: -2.5e30, researchPoints: 9.15e11 }); + }); + + it("reads the clock byte the game writes, and its absence", async () => { + for (const name of TIMELINE_SAMPLES) { + const { timeline } = await sample(name); + expect(timeline?.stampSource, name).toBe( + name === "owner_editor_save" + ? null + : name.endsWith("_server") + ? "server" + : "device", + ); + } + }); + + it("says which clock stamped the export, and not a clock it does not know", async () => { + const read = async (source: number) => + ( + await decodeGameExport( + timelineSection(tinyExport()).f64(0).f64(0).u8(source).code(), + ) + ).timeline?.stampSource; + expect(await read(0)).toBe("server"); + expect(await read(1)).toBe("device"); + expect(await read(7)).toBeNull(); + }); + + it("refuses a timeline that was cut off rather than reading half of it", async () => { + const w = timelineSection(tinyExport()); + w.bytes.length -= 2; + await expect(decodeGameExport(w.code())).rejects.toThrow(/cut off/); }); }); diff --git a/packages/solver/tests/gameExports/editor_current_save.txt b/packages/solver/tests/gameExports/editor_current_save.txt new file mode 100644 index 0000000..3d09924 --- /dev/null +++ b/packages/solver/tests/gameExports/editor_current_save.txt @@ -0,0 +1 @@ +R2X1.jVnLjxw1Gnd193S5ZpkkDEF5TF6wq-WAQMqDJFfoEIhElDATgZCQSp4qd7eZ6nLhqkrS_CFISBw58A8gcVwt2gMnTgghTpxACGlXu3sAaUXhZ9lV7e7FIKbt3-fv-fNndzO-_CL_5_KpiqQoi1GZ4DxFebKMMzxDyTLYjh6QDL-NKszkp9cYKkt4FxXxPk2OnhYfblOGyyqe0JxMMaN1edJZvYUTktZ8Ue65T_N0Z4Ly6pWaZOnrmOEwoTTD7OZxnFQ0Tuii4NtKyrZnOMcMVZTdgGPEMIovB_9rfmme2AF8QAjMiMTQH8OI_wvH8jOEAoACgvwPn3J0KIUEFMKB3gv1fghDIcc_CalIzBwbYHUMR85EfVaeXgkG4IfmxDEjN_Bs9g_pjZ0Kn4W71g0ZVKQ94y4Kj0VgkYpZei3wkJsNeKxQxi7RgRSIpLwxMI5CjQ-1CYHa5Hpjb2EV7dXgn83PzbHjwBgyG4V3oF2KVHXGJjKdejUR9ZH5lyUJIwPDEOoFFaWqXSSjAtIclFraiKCigPW94z7P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aS6iwj3_BFiqQufMvBBRqvSIiNw0SAPyMIXOwBnb-GClqQq7-T82z3_su6Cpw3YU3yJazbQWs1P32YYHxSYY05adsDFO2VmU7Ky8RIA5-8dlhVKMg4v6EOUKRNGIARn7k2nGcnxq4jloiwWC8D5N2uSHIlq-AoFwJ7E9ws_-pyZmJKviW4H_NVMXk1oThfLtYJ7ZnKfkrwqexy50EXv5Al1Y90FL5hJTw0VlfJk_Yxw5A10eHBEii7HOI3eIimmL6e6KP207qDDkmZ1heMPMKNb4KQAyENcxod4SfM0rvgGCHaTOeMhxyhJcKZ-nYHguFrMY37nJHxlCE5wqMRpPGV0IXdugR2ST0lOuIEZIymfF3MuEh_yPUeYjcGJ92uUV_Uixo-TOcpnfMuuWWKYFysRxsbgWaa9jg91mWIuRBao4hSOC86uagzOe4RYYvwbg4ur-CGhC1SWRsNfPBIZSo7iOc2wVXRuVYx7T8s4oQz7YYoyY-SMDxY_hl3egF3ZgF3dgF2D67GXovXY9T-tx25s2HdzAC6tYil5yA-vTaCnnCmli4MKMSv0zKpQ78fCMbiwKjPN6sdWiceZaV0SS9sx2FsVaX-EDH3FbNEr3lq38FW4Eb62eTevzib4-mb4BvQleYZpNcdsYcnoSfKMoYek4md7w6mY44z0VXmO33yZMmpwjz_zZcGPb1mgBOuz47GV45orEf1jIzfyml8fLn_-vCrDeZPUjDMnLpYMLUjqbQqF4AdJ4oo-wn5btkWt7wglqkUO8RJ7U8P7Lne2QDnOvLj6YV6mDvho_oiI9lyzQ36wtnxpEx09LsTVYd3cbcVmqG16O2XFH0HcmSllM7wNduVO0b95vmhFE5ptA_E-_U_zS_PJ6wD8u_m1-ewdwOe_NhfeBODD49--J95lE_0---27bz7_6r-L2x-VT8r5j8-r9QHYTtiS8oI-rssT_f_zIL5YFf9494vxg89f--1j8FP19vuT4Hc \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen0_none_city2.txt b/packages/solver/tests/gameExports/gen0_none_city2.txt new file mode 100644 index 0000000..ded183f --- /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UX2SWFpHiimQ68vhjcWwzcWwzcXw7cWw7eDSd4nrJ4QPm3JGEjyPseHtBZ7e8GumJCc9lUFtt_kaMSZxQP-TI5KsX2rEmfE7J2ArYI0QonsHwu5UTTi-PD58-pQRvAma7hgTloecTyVHSnQFErJD5qlNXtKwrbaFjW_I1S4kTkkRySYGtF3hbMlLkgexGs6alMboLn_n_IklDbZ0dNSHh2tm6ed2D52TW-lqsUlSDgzZlw1YLVS9m-RL1azjOX63vXXqeef9G9mn9_76e4XX-v37o-T139-58utjR_uujvcvw \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen0_none_city2_server.txt b/packages/solver/tests/gameExports/gen0_none_city2_server.txt new file mode 100644 index 0000000..682f30b --- /dev/null +++ b/packages/solver/tests/gameExports/gen0_none_city2_server.txt @@ -0,0 +1 @@ +R2X1.lVhLj9w0HHdiZ7qVum2ptupj--R5ArR9H1u2LVSiatmt4Bh5Mp4ds5k4OEnb5cTn4BNw4ysgOCEOnBAqnDhxQYIjB6TB7ziJZyhZaSb27-__8-e_PTvaekf8baGCFQQcPvyE5uQTXBOu3t7nuKrWHuIy3WHZ_kn5cp9xUtXpNivolHDWVBve7F2S0UkjJtWax6yYrG_jon6vofnkA8LJoYyxnPCtI89oMUnrho9pQdZGmBOcbkX_LP5eHFkH4kEQ2CdaW1tD5jVaOyRGI_kO5bwc2Xc5iqGUl7NrCYzFeyJnD-n1Rkq-CQRFEUTORtzaa58Wlx6pT-3pFRCD3xfHj1q5OLA4_CSRMOspjeQYWTswUg9K4kjDZkI-Dk_sGEYgFqshMqiMN4qQk1b-utXGagSlAt8l1AmzDdVFexX8ufhjcfSYyAfy0yT1xiKErvOjFlSx2IGCxfrYCyIxayCKzbcZa59F-K0i30psPYydCWvVxIn8EGMVoQY6pdLxXQN_LX5anNro5CDEB7E66ecq9LTWOhp7LBlI6KKjnhhSWRuK6-yrdfpTl7HHa8UH9Z14SbQZ7uXW5trSzrkAk5A0iBFyZZZVMGadbih88qIxgtKVTjAj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law-cFSwU07eMxoUVc9jlzoog-KjHVjfdsOemqYrFTA3BnpyId4vLtPyy7HBI0-phPC7kxMUfppXcfjiuVNTdLPCWcAbEiAPiVVOiYHTP4rRiwA4EQ24yLkFGcZyQnHNeMAHNOTRSrOnEzNHBdQRSbplLO5WblOiyktqDCwx-lEjMuZEEnHYs0-kUs-a3BRN_OUPM9muNiTxuwUJ6JYmTb2Kjdep2NTplQI0TmuBYXTUrCrFkQICPGs9e_iEB9TNsdVZTW8HpDIcbafzlhOWkXnhmLCe1alGeMkDDOcWyNnQrD69xdcjl1Zse7qCuzaCuz6CuzGCuzmCuyWaL9DbEKfis3bJjBQzglj890a81bo8lCICEQYmpcCqqTMhaHMNG-et0oCzkybivq03RyK7JHC0jxQTIdeWQ1fXQ1fWw1fXw3fWA3fDCZ5j7B6Rvi8JWMgyXscP6W12NsrdsWM5LSvKrD9ZgcTziwe8Gd2UIrtW5U4I2bvBGwVpBFKZP9YyY2iEceHz5_XhjKCN1nDBXPS8oDjuexIgaZQSn7QLK3ZMxK21bao5R2hwo3MITkgwdSIviucLXFB8iBe00mb2gDN_f-UJ6G0yY6elvLoaN084cT2sGt661UtLkHCmSnjqgGrlbJ_i3yxmmUs1_euH4-_-LR_M_vizs-3x1_r9-6Pkzd-effLh1d_uO0m_gU \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen1_cryo_city41.txt b/packages/solver/tests/gameExports/gen1_cryo_city41.txt new file mode 100644 index 0000000..62483f1 --- /dev/null +++ b/packages/solver/tests/gameExports/gen1_cryo_city41.txt @@ -0,0 +1 @@ +R2X1.lVnNj9xIFS-3Pd12984kRFnlY5JNdlmB9gBSPnZ2r5tJwkYiJMysQOJi1djV3d5xu0zZTjL8BfwP3DjxH3CF5cQfANIKCYkTFyTgxgFoXn25yna52a1u9VS93--9evXq1Yc903vfhc-9ecIuaFyQN02F3oo-y3LyY1wTJmrfY7iqwue4jE9ocv42rzyljFR1fEyLbEkYbaqrlvQxSbK0AaHQeUmLdP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t-_IV60pgnN5f3rv5e-_Jz__UBdjasfvPfrP35-8mR7_Za82Ok3RMj67wJ_Z_OTP3_6y9U_Hz1FPz_-4j-__cUj738 \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen1_singularity_city50.txt b/packages/solver/tests/gameExports/gen1_singularity_city50.txt new file mode 100644 index 0000000..65d7316 --- /dev/null +++ b/packages/solver/tests/gameExports/gen1_singularity_city50.txt @@ -0,0 +1 @@ +R2X1.lVnNj9xIFa_qdrf7a5JJlCgfk69dVnBY7YpMsplInJbJZgkiJMys2KPlsauna8ft6i3byQ4SV84c-CM4wh-AQMuJP4DDwgkuXJAWceKA1Lyqcn3Yru6w5ZbHVb9X7716X1X2DO-_D9f9qwXNT6ss5rQ8j2jBsrikLEc7409oRj6NS8Ll08c8LorR83gVHbHk7Kp4eMo4KcrokOV0TjiriivO6BOS0LSCQTnnJcvTncM4L79f0Sz9AeEkTBjLCD-o_z7eTRlbHpcxjziJk5LxiwTuUcKWK-BXMD45JTnhMSAHl2AoqTgMRqtzHi9pOhrGMC26j_-7_s96toOg4RHSbToaTbF6nMiGh5JCjitoohvuS0BhPQeQM7Bm1deIloExRt3WD5yOelaa7gPvf6x3L5jZnsn-hnFDlLMGuz6xDjVillKTTJwmxTZQ3Fqv1FdRYIlaFi2V2kqa2XK1D_DX63-uL1xETd3rtZghPIILK-cI1eHSEzCewKW6s9HM_OA2tT-4NZrSDCtSLUWRmp4idFSqlQ9cRXvSkX317C5Ure8h_tf6z-trVxo26CNf6w0C73izWWkNjr1Wv02gYj5okU2mcHnIpUmVUqpfmxrsPpkaonE4HocIhePJCC7jqvF0rH5Ai034obFuE8vdcNG_sVHBcBGMQp0ilotsjsaWTyPihoZJMxA9LAwnX8q5g8qzH-C_rr9aX7mJjG7_VwMFO6yFdk2ZwhRjK1N5YdpYIA7qdajV1YPu6ky-1HK0hRxCa2ZXRY9t6sk4FBN7gTtZ-jjAA-yKlkriushh3cxSTHGyxaNbX1Cdz02H1EnatJdM1Y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GIMw-ilNCfswrZ3SNutOfFKwrCpJ9DPC2QBdEQB9RYrohJyzPI1KmDBCl5MFhyVHcZKQTH2vGaKLajDX33Z6aBeggqTRnLOlnDlAOzSf05yCgFNOU-ivFkASncCcMwJMdj-v4ryslhH5IlnE-SkZost6iBNwViKEBehtXmsdndRuioCILuMSQjhaQXSVQ3TbQ8QTrd8Q3e3iJ5Qt46LQHN7xUGRxchYtWEYso1tdMtCeFVHCOPHDLM60kBs-WHwvu78F29-CPdiCPRxtxj4Yb8YeTTZjB1vmPcboXhdL6StIXmtAjzvbnwoH6K0uUevzIUZ3ujTzrPrCSvIoM68KasN2iPa6JOazZOhzpkH3vb428IPRVvjh9tngnW3wo-3MD0KfkU8JKxeEL20weox8yuNXtITc3pIVC5LRNitP-i3OU8407tFncb6C9C1WcULq3PHIykkFTET9sD7zqJ1XsH3Y-Bmib3VpOt-YA19RWIn4oElUstfEL8uWqM0VoYgrYUNyDmXQYxrxUR7UiHOSeU1X0lSbFvnC_DUV5bniJ5BYA5_ZREWPVmLrsGpeNmSnsSl6O0UJhyBQZs64LMBypqjfYC9WsoRlIziBvTkd9Yl5svvVZ-LvL-r-z3_328-__P2jp7_5yy3Z_-Udfarz_59CnPbe_no_-96Pzz7--zu_eveH__7uIf4f \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen2_city52_9c43e4b7.txt b/packages/solver/tests/gameExports/gen2_city52_9c43e4b7.txt new file mode 100644 index 0000000..e87a6fe --- /dev/null +++ b/packages/solver/tests/gameExports/gen2_city52_9c43e4b7.txt @@ -0,0 +1 @@ +R2X1.jVlNjxzFGa6emZ2uXlh7WYz8sTY2JAKJL8kf2D7kAmPsWIrlzS6C5NSq7a6ZKbanq6nutj38jxwiceLET8gRwYkfwAFx4hQFIYGSHIwUpVOfXdU9NRMKxE7V89b7-dRbNcP46lv8n6tnK5KiLEZlgvMU5ckyzvAMJctgO3qfZPhDVGEmP91jqCzhA1TEhzQ5eUF8uEsZLqt4QnMyxYzW5Rln9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fObVRnOm6RmnDlxsWRoQVJvUygEP0gSV_Qx9tuyLWp9RyhRLXKIl9ibGt53ubMFynHmxdUP8zJ1wEfzx0S055od84O15Uub6OhxIa4O6-ZeKzZDbdPbKSv-COLOTCmb4W2wJ3eK_s3zRSua0GwbiPfpv5qnzb_vAfDP5pdm68-Az39p6AEAd3e__Ui8yyb6ffaX136X_fXp4u796jk5_8fran0AthO2pLygT-pyt_9_HsQXq3vJZ_kbf_rbvf9-Cn6oPvx4EvwP \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen2_city52_9c43e4b7_server.txt b/packages/solver/tests/gameExports/gen2_city52_9c43e4b7_server.txt new file mode 100644 index 0000000..4c752ca --- /dev/null +++ b/packages/solver/tests/gameExports/gen2_city52_9c43e4b7_server.txt @@ -0,0 +1 @@ +R2X1.jVlNjxzFGa6emZ2uXlh72Rj5Y21sA0oOUSL5A9ucEIyxsYRlZxcBUiK1artrZirb09VUd9ue3PgD-QU55pCfwBGRXPgBHCyQUE6REFIiuIAg6dRnV3VPzUCB2Kl63no_n3qrZhhf-S3_58rpiqQoi1GZ4DxFebKMMzxDyTLYjt4hGX4PVZjJT3cZKkt4HxXxAU2Onxcf7lCGyyqe0JxMMaN1ecpZvY0TktZ8Ue55SPN0Z4Ly6o2aZOlbmOEwoTTD7NZJnFQ0Tuii4NtKyrZnOMcMVZTdhGPEMIqvBD823zXP7gA-IARmRGLoj2HE_4Vj-RlCAUABQf6HTzk6lEICCuFA74V6P4ShkOOfhFQkZo4NsDqGI2eiPitPrwYD8K9m94SRG3g2-4f0xk6Fz8Jd64YMKtKecReFxyKwSMUsvRZ4yM0GPFYoY5foQApEUt4YGEehxofahEBtcr2xt7CK9lrw7-br5sRJYAyZjcI70C5FqjpjE5lOvZqI-sj8y5KEkYFhCPWCilLVLpJRAWkOSi1tRFBRwPrecZ9nUkGjwHF0MBQzlYBOqVR814P_NJ81p091cjAEvjHYGnnXu2Pk3d9nyYqEyuSoJ2b40Re3kasNujawU99IJ8s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zCMDwvMMSctO-DivTKzKVnZeAmACw-OygolGYcX9BHKlAkjEIKzD6bTjOT4TcRyURaLBeDC72qSHItq-AoFwL7EDwo_-iszMSVfE90O-KWZvJnQnC6WawX3zeQhJXlV9jjyQhe9lyfUjXUP_MZMemqoqJQn62eFI2-jo8NjUnQ5xmn0LkkxfT3VRemndQcdlTSrKxz_CTO6BU4JgDzCZXyElzRP44pvgGAvmTMecoySBGfq1xkITqrFPOZ3TsJXhmCXQyVO4ymjC7lzC-yQfEpywg3MGEn5vJhzkfiI7znGbAx2P6hRXtWLGD9J5iif8S17ZolhXqxEGBuDF5n2Oj7SZYq5EFmgilM4Lji7qjG44BFiifFvDC6u4keELlBZGg0veyQylBzHc5phq-j8qhj3npZxQhn2wxRlxshZHyx-DLuyAbu6Abu2AbsO12OvROuxG8-sx25u2HdrAC6tYil5xA-vTaCnnCmli8MKMSt0eVWo92PhGLywKjPN6idWiceZaV0SS9sx2F8VaX-EDH3FbNGr3lq38DW4Eb6-eTevzib4xmb4JvQleYZpNcdsYcnoSfKMoUek4md7w6mY44z0VXmO33yZMmpwjz_zZcGPb1mgBOuz47GV45orEf1jIzfyml8fLn9eWpXhvElqxpkTF0uGFiT1NoVC8IMkcUUfY78t26LWd4QS1SKHeIm9qeF9lztboBxnXlz9MC9TB3w0f0xEe67ZET9YW760iY4eF-LqsG7utWIz1Da9nbLijyDuzJSyGd4Ge3Kn6N88X7SiCc22gXifftt818R3Afim-b4p3gd8_n3zlF8yX-w-_aN4l030--y_yy_-8NcfFne-rJ6T869-rdYHYDthS8oL-qQud_v_50F8sXr1H39-7cPff3T3f38BX1XvfTAB_wc \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen2_cryo_city34.txt b/packages/solver/tests/gameExports/gen2_cryo_city34.txt new file mode 100644 index 0000000..761d876 --- /dev/null +++ b/packages/solver/tests/gameExports/gen2_cryo_city34.txt @@ -0,0 +1 @@ +R2X1.lVlPj9xEFq-y3f-mp6eHKJBMJiGBXS0nkPJ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qkAGWC82KXM4uLZ7USizOzIqN12fbRfpdSXWQObMms0FvWUqjg28ON8J3Nqw82r75rrbMKhhxZgnxGWD4nfFEXoyXIratb66mYk5i2VVmO33wZiVtdhVv8ad8KW20lpAAlon9srI2kgF8fdf300R-6HKibsOBQOX665MGCRsjWFFJRHzT0c_aU2G21Lq-ticyCQsSQLKEjWEIDfRecTYOExNbQ5TTSobWW-VMq2nPBT-Fg9Wxh616oQyOvaGdB1fQmWQ5fgsCZGeNnotvLlaJ_Q7xYzkIWq5uTF3a_-0B8_rn8avz-Z_8--s_nn9z7xzt7cv5NKXeQ8f8Tu2ojQRaSJAqScClIX3v_uvCT599HX3yM3_30g7fwrw \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen2_singularity_city32.txt b/packages/solver/tests/gameExports/gen2_singularity_city32.txt new file mode 100644 index 0000000..dfb7890 --- /dev/null +++ b/packages/solver/tests/gameExports/gen2_singularity_city32.txt @@ -0,0 +1 @@ +R2X1.lVnNj9y2FSdHHzOenZndLGz4Y-3YTpP01AS2d-0gt2TtNAa6sLObtEAvAkfi7DCrESeUZGf7F_XPKBogQM9FDkF7yamXAs2p6KHA9JEURUnDmaRc7azI3-N7j-_9-Ebihg_eg58H13KWnZcpEay4jFjOU1IwnqG9K5-zlP6OFFSou18LkueDE7KMTnl8cU3efMIFzYvomGdsRgUv86uN0ac0ZkkJg2rOS54l42OSFR-XLE0-pYLuQYctSAH6o2UKnf1pSuKLaM5TGglK4oKLfsyhJw6rv0fDc5pRQQA5tLdHu-eCvGKF4JlWtDe_XILSfEliGsXgzf4fwLtoyVlWGM2DkMBd9AD_d_Wf1WiMoOE-Mg3j_k7Vu6IaDuU9DMJ9vy8h-IQuXNhT8n0J4Z6811N8rVPJwJ2np_T71gZG683zGx19rz19CLr_sdqbGLmeY7K7YdwyNR6Psfw16M5wR_6Od8a6P65-hloEV_KAQ9_DqJLXKsELI1-bCLGag9WatQNSvukS4B0n62Xr1T7C_1r9czXZBYN40FrLCBTXtg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YO0X0D58c8L07KtGDLlFFhZQL0xjHJ58dkacdG6OYxvKA_pQuSJZVta3IiMTtwD92SA2elWKZl3pFG6Da8sRcC3oNPCAPPXxORNOHrBj5LeZFbxEN3DfI5W7jWjtCtp3TJc1bkzzN4sad5K3Y3DNhRfA80G2ij5mufCErPlhSwRliuoLvP89SGZG3iPYTuvJjmBYlTgBf8FUm1CRvsmy9ms5Rl9BkRmUyLxTC681nJ4guZDVeiEDpQ-OnSjf7SdEzKN6xugN41nWcxz_jicqPggem8lMcZeYsjO-jNNvo8i3lzrTvoV6bTUcNlphxRvykd-Q2Znl2wZZtjQKPfsoTyj5IqKe2w9tGYTHOelgWN5PELRlclwF7RPJrSS54lUQETQrQfzwUsOSJxTFN9ohOiXT2YmeMahPYAymkSzQRfqJkYjVk2YxkDA-eCJdBfzkEkmsKcCyow2vuqJFlRLiL6dTwn2TkN0L4ZEhSSFUtjPfSWqLyOplWaou7ZVIjuOIREbPwL0d11fMr4guS51hCgtx0SaydeIbq9Lgbe81ydZCEnzElq3LzpguXZ2YMt2MMt2KNgM3Y42IwdbcEeo83Yky3YB1B-17GEvYLNa5niSGfC-eKsIMIK3V8XooCAocUSoFzKvLkuM0vLr60ShzOzMmeWtiE6WBepDy6dua7Rh9vhR4Ot8OH22UfBVvixk2c1_MQZ5HPKizkVC0PGwBXkzlFt6NoVc5qyrirH9ptfJvJUV-MOf7qnwE5bGS1BiawfW7mRlfD1YfkTol-sywBv4lIAc6LlpSALliBXUVhKfrA4Kvhr6rZlS9TmipCTUsaQXkJFcIRGHuKDGySjqe_CC5aY0Dpp_prJ8lyKKWwsZ-FaP1Dvof1a7JzURW-cF_AQBM7MuDinIKRmyvoN8eIFj3kawBPYzzJhHu3e2vv-S_n30-op-sf9H74YfUie3v_9vup_ax7qkftfG3Ladxf__vvJ--88Q-jsw7-ePPsY_w8 \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen3_tidal_city31.txt b/packages/solver/tests/gameExports/gen3_tidal_city31.txt new file mode 100644 index 0000000..173da18 --- /dev/null +++ b/packages/solver/tests/gameExports/gen3_tidal_city31.txt @@ -0,0 +1 @@ +R2X1.jVnNjxtJFa_qL8-0x_ZslFUymWSTAIITKyWZSVbcdmd2l0gbJcys4Nhqd5fHxbS7muruJObCgRtH7lw48WcgOHFF4rDaEwiJCwLEiQOSqc_u6u6ySY1id73f-36vnu1K8OhD9vfosMJpnEVxmaA8jfNk7by3_yXO0I_iClHx9DmNy3LvRVxEFyS5fp8_fEYoKqvojOR4gSipy5sG9RwlOK0ZUci8Ink6OYvz6pMaZ-n3EUU35lmcXEdLkqGIojipCB0lhO3oI_V-ot5PwyuUIxozjpP28XR2RePXuKIkj4qMaT5crgtEo7KIExQlzInZT2pGrlda_cEbnKdRVdM5ztFeEDNy9Aj-d_OfzcEEsDU9AHpNp-F0qh8PwoPpNJAcYcg3U8kSyp0rAcg3jhRgS8qzDRdnT5yL7bRasQPDdbhnbsSr9PQxdMDfNodaxnUswvY14cvYjvlqKJMx8xyGDWUyhmJxisYVge0hbAkcdYS-sNkLfxWHiFk6wFm6Lo37TjbSIton8J-bv2-mMxB2fAfS87EmhZBpHk8CHYqIZGL6LcKYGEGMJ-GY_41VTKFQKfBQsE6UbDg2UwSNHbdpxqKc98wQHdcDOgGdUsn4TuC_Nn_a3LrZyYELbMvxPSu9u1prHY29LhlwzGZCuMe2P94XQJ99nwEySCkAoRCf7fPVqGTPY0afMV4oniR5LOj8zSRLYUZh_9hLS-bSahlkzt6QuRJvwG7o1q5xFa2DfAXjfe5PE0-bj9m-jr6fEwsRQMM1WdlT-PXmq83NO6Dx7Z3WaDQaUg761JEYQA3RUUTWrA0r9LSwwQq1SskadO3w1lfiOhtMWirtGoeC2BcW4twdFbCicUYP-rBxki0hDF3JOArlqRw1oWgP-fBoXNHxmVa5K13vwoODvsOsaJyzn1gu3qV5gthn27o8OKRBC03olV3xFP5589vN7ds9BvuJ751HrllmbGjEZtVGA-Ys2MIA4EA_9CVZII7J6HrquPlKu6A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AbhnYaKJ9i8A94f4HJNVXJZaw7csHIM7sADcHbIx70kp7rSAFSZxpo0c2WBxq7YDe7wDe7IDO9nbjp3ukHsKtmPPdmAfsfE7xFL8mh1enUBgK2dKyOqyimnL9HDIhBjCDK0KBpWc54MhzyKr37ZKLM4s6hK3bRuA4yFLc4U5shWzQR9bW6GBn-zthE92S596O-Gn1j5r4GfWJF8hUi0RXbXNaEly79LWeiqWKMN9VZbjt1ynlGjc4k__Pti12cpRzZTw-bGzN_KafXy0_ROAbw55WN8kNWWdExVrGq9wCmxDoeD9gZOoIm-Q3Vbv2tpayDKueQ7Rmk0ES2rY3GXOFnGOMmvq5G2_SJ21zc2bct-WNj7Ro4J_dLRpu9GwXcXN0JuUFfsSxJxZECoGsJDk85vli1QkIZm88f7w8Ksf8_c_qq_Gfz36xc_ffv35-S838hb8V_qbOhj8XwX_yvfvn_3le_N__PocgC_Ws_HDT-D_AA \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen6_tidal_city49.txt b/packages/solver/tests/gameExports/gen6_tidal_city49.txt new file mode 100644 index 0000000..94787ea --- /dev/null +++ b/packages/solver/tests/gameExports/gen6_tidal_city49.txt @@ -0,0 +1 @@ +R2X1.jVlPjxxHFa_a6Z3q7mSdtWXLf9YbOxDBCaS1HW_ELazjYCmWzW6AA4dWbXftTGd7ujrV3bYnh5z5DOELcELKN0BwgjuHCHHggLgggYiEOICGV6-6-t_UbFLr3Zmq36v3Xr33e696xtOD78PPwfUqTXgW8TIWecLzeBllYsbjJX0t-CjNxM94JRS--0DxsvSf8iI6lvH5Nf3msVSirKIjmadnQsm6vNpbfSTiNKlhEfc8l3myc8Tz6od1miU_EkqwWMpMqMPdRMrFScVVpASPK6nCmciF4vDu8HKhRFyrUqqoWCq-SBN_ykEsOqD_Xf1n9foOgeH7xA4WMDujPvMD35-iREApZQFCIBAwymA2AYBRjTB_SwvBMuxnuIPBFj-Ad1rKb_YSY46R9THxehPz3nh6j26Rv612L1m5Lcdm9whZGPZMsS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TITkCu7U_RviJSsZy8w8y_1g98uP9esXzXPYz__9i19__r_9x2znCs7_um_WJySM1VJC4l7V5bUSnKlBPdxMUapPre-v3fF_RejPin84_OqXn31174MP__zF5__6ydtH9P8 \ No newline at end of file diff --git a/packages/solver/tests/gameExports/gen6_tidal_city49_server.txt b/packages/solver/tests/gameExports/gen6_tidal_city49_server.txt new file mode 100644 index 0000000..0c1db16 --- /dev/null +++ b/packages/solver/tests/gameExports/gen6_tidal_city49_server.txt @@ -0,0 +1 @@ +R2X1.jVlPjxxHFa_a6Z3q7mSdtWXLf9YbOxAlJ5DWdry5hnUcLNmy2Q1w4NCq7a7Zabanq6nutj0c4MpnCF-AE1K-AYIT3DlEiAMHxAUJRCTEATS8etXV_6Zmk1rvzlT9Xr336r3fe9Uznh58G34OrldpwrOIl7HIE57HyygTZzxe0jeCT9NM_JBXQuG7TxQvS_8ZL6JjGZ9f028eSyXKKjqSeToTStbl1d7qIxGnSQ2LuOeFzJOdI55X36nTLPmuUILFUmZCHe4mUi5OKq4iJXhcSRWeiVwoDu8OLxdKxLUqpYqKpeKLNPGnHMSiA_rf1X9Wb-4QGL5P7GABszPqMz_w_SlKBJRSFiAEAgGjDGYTABjVCPO3tBAsw36GOxhs8QN4p6X8Zi8x5hhZHxOvNzHvjaf36Bb522r3kpXbcmx2j5CFYc8UC0L4YaGdMhbCbwD_jLQGg1BLhBYP8U8ASiaUIAq_qBK80CgItwrJNNAwSjcmQi0zcCkYn72dm9Pep_9Y_X116S0IYC8tRBuHebuEAQ3Y1M6Y_hcgCq-wFaZaPtBqAv0C8igWIILbcckIM4LmYAGlWyuMdW74OlQ9n7R-fOPRnqNbmEgTgEGqzPke0H-u_ri6fnUQgwlxja1tz7k-HJ21gcYRS9YkTBa9kRikB9M5Fmc6r8YpMzfbAyRItzlEqRApE3Q8C5BFIb50-dfMAUjTLejxVItpHrGhtCGzYSNKe624WQkH0pq9yM5gUAKao8xoav1r9DT0Xy9NxhyLpL_fZPYD-qfVF6urt0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fx9zleu0dBgl-9-r0_hcZ8OVKEL2ED8u3Oj7dmJTvuF0IXnPTj6OZS4Xy42Ce3byQqZ5VY448vYQfZLHsn_Wy-RbdjJSI3WmHFG_qR15yk9PztNiyDGg0Q_SRMiPkiYp47Du8NNSZnUlop8KJRm5qoH0pSijU7GUeRJVsIGRK_FcwZEjHsciM9_XTMlbZjG33-Vsk12ASpFEMyUXuHOb7KT5LM1TMHCm0gQMFnMQiU5hz7kAJbs_qXle1YtIvI7nPD_TxuySEpCsWBvzyDdU43V02qQpAqF0wSugcFQAu6op2XcIqdj6NyV31vHTVC54WVoN7zokMh6fR3OZiU7R7XUx8F6WUSyV8Jyw5Jk1ctMF6-_HDi7A7l2A3b8Ae-Bvxj4INmMP39iMHbLN2IfQftexJH0JxdsF0JHO8VeDU_LOupAABAwtCoBKqQh5e11mltWvOyUOZ2Z1mXa0nZK9dZH2a0nmSmaL3nNSoYXv-xfCDy7eDdm5CH54sWuH264gnwlZzYVadGR0BPlM8ZdpBbV9QVXMRZaOVTnKb75MlLS4w5_5soDyLQseC6wdp61c1KBE9w-bM8_ldl7D9dHnzzfXZda-Y6auplBofqRxVMlXwm2ra1GbO0LJax1DsRTO0EDfBWcLnovMiZvv6jF0Tpq_SnV7rtUpFNa2K2y6o0eFvjo6N6-0Yme8bXo7ZQUPQeDMTKozEZIruFP3b4iXrGQsM_Ms9_PdL36sXz9vnsN-9O9f_Pqz_-0_frpzBed_3TfrExLGaikhca_r8loJztSgHm6mKNWn1vfX7vi_IvRnxT8cfvnLn31575Onf_78s399_90j8n8 \ No newline at end of file diff --git a/packages/solver/tests/gameExports/owner_editor_save.txt b/packages/solver/tests/gameExports/owner_editor_save.txt new file mode 100644 index 0000000..f9b0c25 --- /dev/null +++ b/packages/solver/tests/gameExports/owner_editor_save.txt @@ -0,0 +1 @@ +R2X1.jVnLj9y2GSclzWhmZ8feLBz4sXbsPJDkkAf83FyTtd0aqGFnN0iOglbi7DCrERVKsr35C4Lcc-2ph_wTAYr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8yyJOkDo7Dlv9N8NOt_OafX2Y-hmD1_s8rG6SmrLKiYozGq9wClxNoeD1gZOoIs-R25ZpUcMdoYxrHkN0hpyhYX2XOVvEOcqceIVTHVpnmT_HvD3X9JgdrJErbLyjRwX_6jBu7jZsJ3HT9OZlxS5BzJkFoSfIB7tCkvdvFi9SkYRkW-Le9R388XP-73vqHva_56vfvv3O9w--ARfFOjqvb2vWf0Dwq9t_vvr31T_nf3v49dHqd8mjnz76Pw \ No newline at end of file From 38e78cef15c25ad227273e069e9d58e72129122f Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:33:57 +0300 Subject: [PATCH 3/9] Show every island's power and the Chronon count in the header - @reactor2/solver gains data/chronons.ts: the game's award formula, its inverse, the jump threshold by generation, the first-entry bonus and projectTimeline, which runs an export's timeline forward from its export time. Held to the award in every 1.1.11 sample and to a live reading on a player's save. - timelineState adds up every game island's power live (the board on screen from its placements, the rest from their saved layouts) and projects the Chronon count at the power the game's own boards made. - A game import is now kept as the game had it (game_import): the full research map, research in progress, obstacles being cleared, each island's board, the export and import times and the timeline, for the planned move list and spending tools. - The header shows both in a pill whose panel adds the next Chronon, the jump threshold, the first-entry bonus still available, Chronons held and the timeline's length. The Chronon icon is the game's own. When the export was stamped by the device clock rather than server time, the panel says the countdown may be off. --- CLAUDE.md | 5 +- docs/game-logic.md | 19 + packages/solver/CLAUDE.md | 11 + packages/solver/src/data/chronons.ts | 166 +++++++++ packages/solver/src/index.ts | 1 + packages/solver/tests/chronons.test.ts | 155 ++++++++ public/icons/icon_chronon.webp | Bin 0 -> 2678 bytes src/lib/components/header/Header.svelte | 8 + .../components/header/TimelineStatus.svelte | 336 ++++++++++++++++++ src/lib/simulation/simulator.ts | 25 ++ src/lib/state/CLAUDE.md | 39 +- src/lib/state/index.ts | 4 +- src/lib/state/timeline.svelte.ts | 252 +++++++++++++ src/lib/state/timeline.test.ts | 165 +++++++++ src/lib/state/ui.svelte.ts | 20 +- src/lib/storage/storage.ts | 55 +++ src/lib/utils/formatters.ts | 17 + 17 files changed, 1272 insertions(+), 6 deletions(-) create mode 100644 packages/solver/src/data/chronons.ts create mode 100644 packages/solver/tests/chronons.test.ts create mode 100644 public/icons/icon_chronon.webp create mode 100644 src/lib/components/header/TimelineStatus.svelte create mode 100644 src/lib/state/timeline.svelte.ts create mode 100644 src/lib/state/timeline.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 5b7cbbd..f95b71d 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -219,7 +219,7 @@ down**, and after `npm run fixtures` **read the diff**. See ## State layer (`src/lib/state/`, Svelte 5 runes) -Six singleton classes, each exported as a ready-made instance, split by what the +Seven singleton classes, each exported as a ready-made instance, split by what the state **is** rather than by which component reads it. They reference each other directly rather than through events/props — this is a small enough app that singletons + direct calls are the whole store layer. What keeps that from @@ -228,7 +228,8 @@ becoming a knot is that the references form a **strict DAG**: ``` layout -> (nothing) config -> (nothing) viewport -> (nothing) editor -> layout -solver -> config, layout ui -> config, layout, solver, viewport +solver -> config, layout timeline -> config, layout +ui -> config, layout, solver, timeline, viewport ``` ## Assets and the deployed base diff --git a/docs/game-logic.md b/docs/game-logic.md index c81a8e4..ed120d8 100755 --- a/docs/game-logic.md +++ b/docs/game-logic.md @@ -392,6 +392,25 @@ apply them, and the cooling network. The in-game description text is not the authority: several of its lines have more than one consistent reading, and where it and the code differ, what is written here is the code. +### What a Time Jump pays + +A jump pays Chronons for the energy the timeline produced, online and offline: + +``` +Chronons = max(1, floor(97.34 × (E / 2.82e16)^0.135 × M)) + B +``` + +`M` is the Chronon Reactor research's multiplier (×1.05 to ×1.25), and `B` is +88 the first time a timeline runs under a given anomaly, otherwise 0 — added +after the multiplier, not through it. At zero energy the award is 0. A jump is +allowed once the award without `B` reaches +`min(5000, round(88 × 1.15^jumps completed))`: 88, 101, 116, 134 … + +**Layout power barely moves the count.** At an exponent of 0.135, doubling a +whole timeline's energy pays about 9.8% more Chronons; what layout power buys is +_when_ the next one arrives. The board's power is energy per 3-second tick. +`packages/solver/src/data/chronons.ts` holds the formula. + --- ## Time Lab Research diff --git a/packages/solver/CLAUDE.md b/packages/solver/CLAUDE.md index f188a38..bd1c48d 100644 --- a/packages/solver/CLAUDE.md +++ b/packages/solver/CLAUDE.md @@ -79,6 +79,17 @@ by `HeatProducerBuildingSO`. That is why Infinite Grid goes out of its way to name turbines. The rule is "every heat producer", and a reactor is the only one the game ships, so it is modelled as reactors. +### Chronons + +`data/chronons.ts` is the one place the game's Chronon award lives: the formula, +its inverse (`energyForAward`), the jump threshold by generation, the first-entry +bonus and `projectTimeline`, which runs a game export's section 7 forward from its +`exportedAt`. Chronon Reactor's multiplier is carried there rather than in +`PRESTIGE_UPGRADES`, which holds only research a layout can feel. Island power is +energy **per tick** (`TICK_SECONDS` = 3). `tests/chronons.test.ts` holds the +formula to the award the game wrote into every 1.1.11 sample, and the projection +to a live reading taken on a player's save. + ### Anomalies Prestiging also picks an **anomaly** that changes the rules for the whole next diff --git a/packages/solver/src/data/chronons.ts b/packages/solver/src/data/chronons.ts new file mode 100644 index 0000000..21e8b8e --- /dev/null +++ b/packages/solver/src/data/chronons.ts @@ -0,0 +1,166 @@ +import type { GameExportTimeline } from "../encoding/gameExport"; + +/** + * What a Time Jump pays, and when the next Chronon lands. + * + * The award is the game's `ChrononFormula`, read out of its binary and then + * stated by its developer in the same form: + * + * Chronons = max(1, floor(97.34 × (E / 2.82e16)^0.135 × M)) + B + * + * `E` is the timeline's energy, online and offline; `M` the Chronon Reactor + * multiplier; `B` the first-entry bonus — 88 the first time a timeline runs + * under a given anomaly, otherwise 0, and added after the multiplier rather + * than through it. At `E = 0` the game pays 0, not the `max(1, …)` floor. + * + * Every sample the game exported carries its own award, and this formula + * reproduces each one (`tests/chronons.test.ts`). The projection was then held + * against a live save: from the export's figures and the board's power taken + * per 3-second tick, it put the next Chronon within two seconds of the game's. + * + * The exponent is the fact that matters to a player: doubling a whole + * timeline's energy buys about 9.8% more Chronons. The multiplier and the + * first-entry bonus are the levers that move the count; layout power mostly + * moves how soon it arrives. + */ + +const AWARD_BASE = 97.34; +const ENERGY_SCALE = 2.82e16; +const EXPONENT = 0.135; + +/** `B`: paid on a timeline's first entry into an anomaly, unmultiplied. */ +export const FIRST_ENTRY_BONUS = 88; + +/** + * Seconds per game tick. A board's power — what `simulateIsland` totals, and + * what the readout prints — is energy per tick, so this turns it into the rate + * timeline energy grows at. + */ +export const TICK_SECONDS = 3; + +/** + * Chronon Reactor's authored `BonusPercentage` per level, from the external + * extractor's Time Lab record. It is one of the nine researches + * `PRESTIGE_UPGRADES` leaves out, since it changes no layout; it is carried + * here because it is the `M` above. + */ +const CHRONON_REACTOR_BONUSES = [0.05, 0.1, 0.15, 0.2, 0.25] as const; + +/** The game's research id for it, as a game export spells it. */ +export const CHRONON_REACTOR_ID = "chronon_reactor"; + +/** `M` at a purchased level — 0 means not bought, and is ×1. */ +export function chrononMultiplier(level: number): number { + if (!(level > 0)) return 1; + const i = Math.min(level, CHRONON_REACTOR_BONUSES.length) - 1; + return 1 + CHRONON_REACTOR_BONUSES[i]; +} + +/** Chronons a jump pays for `energy`, without the first-entry bonus. */ +export function chrononAward(energy: number, multiplier: number): number { + if (!(energy > 0)) return 0; + return Math.max( + 1, + Math.floor(AWARD_BASE * (energy / ENERGY_SCALE) ** EXPONENT * multiplier), + ); +} + +/** + * The timeline energy at which the award first reaches `award` — the inverse + * of `chrononAward`, up to its floor. + */ +export function energyForAward(award: number, multiplier: number): number { + if (award <= 1) return 0; + return ENERGY_SCALE * (award / (AWARD_BASE * multiplier)) ** (1 / EXPONENT); +} + +const THRESHOLD_BASE = 88; +const THRESHOLD_GROWTH = 1.15; +const THRESHOLD_CAP = 5000; + +/** + * The smallest award (bonus excluded) the game lets a player jump on, after + * `generation` completed jumps: 88, 101, 116, 134, 154 … capped at 5000 from + * the 29th. Rounded half away from zero, which on a positive number is what + * `Math.round` does. + */ +export function jumpThreshold(generation: number): number { + return Math.min( + THRESHOLD_CAP, + Math.round(THRESHOLD_BASE * THRESHOLD_GROWTH ** Math.max(0, generation)), + ); +} + +/** + * The anomaly a first-entry bonus is filed under. A rebalance is still the + * same anomaly — the game writes `tidal_ascendancy` into the entered list + * whichever balance the save runs — so a balance-variant id folds back. + */ +function bonusAnomaly(anomalyId: string): string { + return anomalyId === "tidal_ascendancy_legacy" + ? "tidal_ascendancy" + : anomalyId; +} + +/** `B` for a jump into `anomalyId`, given the anomalies already entered. */ +export function firstEntryBonus( + anomalyId: string, + entered: readonly string[], +): number { + if (anomalyId === "none") return 0; + return entered.includes(bonusAnomaly(anomalyId)) ? 0 : FIRST_ENTRY_BONUS; +} + +/** Where a timeline stands at one moment, projected from an export. */ +export interface TimelineProjection { + /** Seconds since the export the projection ran forward. */ + sinceExport: number; + energy: number; + elapsedSeconds: number; + /** Chronons a jump pays now, first-entry bonus excluded. */ + award: number; + /** Seconds until the award goes up by one; null when energy is not growing. */ + secondsToNext: number | null; + /** The award a jump needs, and whether this one clears it. */ + threshold: number; + canJump: boolean; +} + +/** + * Runs an exported timeline forward to `atUnixSeconds` at `energyPerSecond`. + * + * A code is a photograph: it may be pasted minutes or days after the game + * wrote it, and the timeline kept running in between — offline time counts + * too. So nothing is shown as the export's own figure; everything is carried + * forward from `exportedAt`. A clock behind the export's (a device clock, or a + * server time ahead of it) projects nothing rather than running backwards. + * + * The rate is the caller's to choose, and the right one is the power the + * player's game boards make — not a board edited here since, which the game + * has not seen. + */ +export function projectTimeline( + timeline: Pick< + GameExportTimeline, + "exportedAt" | "energy" | "elapsedSeconds" | "generation" + >, + energyPerSecond: number, + multiplier: number, + atUnixSeconds: number, +): TimelineProjection { + const sinceExport = Math.max(0, atUnixSeconds - timeline.exportedAt); + const rate = energyPerSecond > 0 ? energyPerSecond : 0; + const energy = timeline.energy + rate * sinceExport; + const award = chrononAward(energy, multiplier); + const next = Math.max(energyForAward(award + 1, multiplier), energy); + const threshold = jumpThreshold(timeline.generation); + return { + sinceExport, + energy, + elapsedSeconds: timeline.elapsedSeconds + sinceExport, + award, + secondsToNext: rate > 0 ? (next - energy) / rate : null, + threshold, + canJump: award >= threshold, + }; +} diff --git a/packages/solver/src/index.ts b/packages/solver/src/index.ts index 013d414..7204812 100644 --- a/packages/solver/src/index.ts +++ b/packages/solver/src/index.ts @@ -30,6 +30,7 @@ export * from "./solver/solver"; export * from "./data/anomalies"; export * from "./data/buildings"; +export * from "./data/chronons"; export * from "./data/effectiveBuildings"; export * from "./data/gameImport"; export * from "./data/maps"; diff --git a/packages/solver/tests/chronons.test.ts b/packages/solver/tests/chronons.test.ts new file mode 100644 index 0000000..40d69bb --- /dev/null +++ b/packages/solver/tests/chronons.test.ts @@ -0,0 +1,155 @@ +/** + * The Chronon award against the game's own: every 1.1.11 sample carries the + * award the game computed, and the formula has to land on each one exactly. + */ +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { + CHRONON_REACTOR_ID, + chrononAward, + chrononMultiplier, + energyForAward, + FIRST_ENTRY_BONUS, + firstEntryBonus, + jumpThreshold, + projectTimeline, +} from "../src/data/chronons"; +import { decodeGameExport } from "../src/encoding/gameExport"; + +const DIR = join(dirname(fileURLToPath(import.meta.url)), "gameExports"); + +describe("chrononAward", () => { + it("reproduces the game's award in every sample", async () => { + // Every sample but the three written before the timeline section. + const names = readdirSync(DIR).filter((f) => !f.startsWith("city")); + expect(names.length).toBe(13); + for (const name of names) { + const exp = await decodeGameExport(readFileSync(join(DIR, name), "utf8")); + const t = exp.timeline!; + const m = chrononMultiplier(exp.research[CHRONON_REACTOR_ID] ?? 0); + expect(chrononAward(t.energy, m), name).toBe(t.jumpAward); + } + }); + + it("pays nothing at zero energy, and at least one past it", () => { + expect(chrononAward(0, 1)).toBe(0); + expect(chrononAward(1, 1)).toBe(1); + }); + + it("takes the multiplier inside the floor", () => { + // The live save: E 1.77717e31 at Chronon Reactor 3 paid 11140. + expect(chrononMultiplier(3)).toBe(1.15); + expect(chrononAward(1.77717e31, 1.15)).toBe(11140); + }); +}); + +describe("chrononMultiplier", () => { + it("is ×1 unbought and clamps past the last level", () => { + expect(chrononMultiplier(0)).toBe(1); + expect(chrononMultiplier(5)).toBe(1.25); + expect(chrononMultiplier(9)).toBe(1.25); + }); +}); + +describe("energyForAward", () => { + it("is where the award first reaches each count", () => { + for (const m of [1, 1.15, 1.25]) { + for (const n of [2, 134, 6905, 11221]) { + const e = energyForAward(n, m); + expect(chrononAward(e * (1 + 1e-12), m)).toBe(n); + expect(chrononAward(e * (1 - 1e-9), m)).toBe(n - 1); + } + } + }); +}); + +describe("jumpThreshold", () => { + it("grows by 15% a jump and caps at 5000", () => { + expect([0, 1, 2, 3, 4, 6].map(jumpThreshold)).toEqual([ + 88, 101, 116, 134, 154, 204, + ]); + expect(jumpThreshold(28)).toBeLessThan(5000); + expect(jumpThreshold(29)).toBe(5000); + expect(jumpThreshold(60)).toBe(5000); + }); +}); + +describe("firstEntryBonus", () => { + it("pays once per anomaly, and a rebalance is the same anomaly", () => { + const entered = ["cryo_nexus", "tidal_ascendancy"]; + expect(firstEntryBonus("singularity_isolation", entered)).toBe( + FIRST_ENTRY_BONUS, + ); + expect(firstEntryBonus("cryo_nexus", entered)).toBe(0); + expect(firstEntryBonus("tidal_ascendancy_legacy", entered)).toBe(0); + expect(firstEntryBonus("none", [])).toBe(0); + }); +}); + +describe("projectTimeline", () => { + /* + * The live check this was built against: a save exported at 12:41:17 UTC, + * 12d 23h 6m into its timeline, with 1.5374e26 power across its eight + * islands. The game's counter read 11220 at 13d 4h, and each Chronon after + * it took 4 minutes and a second or two. + */ + const timeline = { + exportedAt: 1792586477, + chronons: 67, + energy: 1.77717e31, + elapsedSeconds: 1119984, + jumpAward: 11140, + anomaliesEntered: ["cryo_nexus", "tidal_ascendancy"], + generation: 2, + }; + const perSecond = 1.5374e26 / 3; + + it("reads the export's own figures at the moment of export", () => { + const p = projectTimeline(timeline, perSecond, 1.15, timeline.exportedAt); + expect(p).toMatchObject({ + sinceExport: 0, + award: 11140, + threshold: 116, + canJump: true, + }); + }); + + it("lands Chronon 11220 inside 13d 4h, four minutes a Chronon", () => { + const at = (award: number) => + timeline.exportedAt + + (energyForAward(award, 1.15) - timeline.energy) / perSecond; + const elapsed = at(11220) - timeline.exportedAt + timeline.elapsedSeconds; + expect(elapsed).toBeGreaterThan(13 * 86400 + 4 * 3600); + expect(elapsed).toBeLessThan(13 * 86400 + 5 * 3600); + + const p = projectTimeline(timeline, perSecond, 1.15, at(11223) + 1); + expect(p.award).toBe(11223); + expect(p.secondsToNext! + 1).toBeCloseTo(at(11224) - at(11223), 6); + expect(p.secondsToNext! + 1).toBeGreaterThan(239); + expect(p.secondsToNext! + 1).toBeLessThan(243); + }); + + it("never runs backwards on a clock behind the export", () => { + const p = projectTimeline(timeline, perSecond, 1.15, 0); + expect(p.sinceExport).toBe(0); + expect(p.award).toBe(11140); + }); + + it("has no next Chronon on a board making nothing", () => { + const p = projectTimeline(timeline, 0, 1.15, timeline.exportedAt + 999); + expect(p.secondsToNext).toBeNull(); + expect(p.elapsedSeconds).toBe(timeline.elapsedSeconds + 999); + }); + + it("refuses a jump below the generation's threshold", () => { + const p = projectTimeline( + { ...timeline, energy: 87, generation: 3 }, + 0, + 1.1, + timeline.exportedAt, + ); + expect(p).toMatchObject({ award: 1, threshold: 134, canJump: false }); + }); +}); diff --git a/public/icons/icon_chronon.webp b/public/icons/icon_chronon.webp new file mode 100644 index 0000000000000000000000000000000000000000..80e6ed46b56daaf920c3a4224a03eecc41c1a966 GIT binary patch literal 2678 zcmV-+3W@bnNk&F)3IG6CMM6+kP&iCs3IG5vA3z5XCh7qIoQ|Xvv*-Bvy|r!Io0)iQ z+qP}TcE&HsaBc4vaK@m8uYzkKbzDhT{QSG>^K&b>l4W7rb~aMh_7*AAG^)+9XV$iD z<7n(X@*df?ZEI|+)3H^2(x`1OBW>2UZSP=hYn(P|I$GQI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zV3uLwY*AE;H
+ + + {#if showSize} {/if} diff --git a/src/lib/components/header/TimelineStatus.svelte b/src/lib/components/header/TimelineStatus.svelte new file mode 100644 index 0000000..b1ac3d7 --- /dev/null +++ b/src/lib/components/header/TimelineStatus.svelte @@ -0,0 +1,336 @@ + + +{#if visible} + + +
+
+

All islands

+
+
Power
+
{formatNumber(power)}
+ {#if diverged && gamePower !== null} +
In the game at export
+
{formatNumber(gamePower)}
+ {/if} +
+
+ + {#if projection && record?.timeline} +
+

Timeline

+
+
Jump now
+
+ + {count(projection.award)} +
+ {#if bonusNames} +
First entry
+
+88 for {bonusNames}
+ {/if} +
Next Chronon
+
+ {projection.secondsToNext === null + ? "—" + : `in ${formatSpan(projection.secondsToNext)}`} +
+
Jump needs
+
+ {count(projection.threshold)} · {projection.canJump + ? "ready" + : "not yet"} +
+
Chronons held
+
{count(record.timeline.chronons)}
+
Timeline
+
{formatSpan(projection.elapsedSeconds)}
+
+
+

+ From your game export {formatTimeAgo( + record.timeline.exportedAt * 1000, + timelineState.now, + )}, game {record.gameVersion}. Counted forward at the power your game's + boards made then; re-import after changing them in the game. +

+ {#if record.timeline.stampSource === "device"} + +

+ The game hadn't synced its clock when it exported, so the countdown + may be off by as much as your phone's clock is. +

+ {/if} + {:else} +

+ {record + ? "Your last import is from before game 1.1.11, which has no timeline." + : "Import your game's code to count your Chronons here."} +

+ + {/if} +
+{/if} + + diff --git a/src/lib/simulation/simulator.ts b/src/lib/simulation/simulator.ts index 5cf6a77..0154eed 100755 --- a/src/lib/simulation/simulator.ts +++ b/src/lib/simulation/simulator.ts @@ -172,6 +172,31 @@ function layoutFor( return { placement, rowOf }; } +/** + * The total power of a board that is not on screen — one of the islands the + * header adds up, or a game board as it was imported. + * + * Its own context rather than `contextFor`'s: that cache holds one board, the + * one being edited, and walking eight islands through it would evict it eight + * times over and make the next edit pay to rebuild it. Callers here run on a + * change of island or roster, not on every edit, and memoise the answer. + */ +export function boardPower( + grid: Tile[][], + buildings: readonly BuildingDefinition[], + placedBuildings: readonly PlacedBuilding[], + prestige?: PrestigeScales, + anomaly: AnomalyDefinition = getAnomaly(undefined), +): number { + if (!grid?.length || !grid[0]?.length || placedBuildings.length === 0) { + return 0; + } + const ctx = buildIslandContext(grid, undefined, anomaly); + if (ctx.n === 0) return 0; + const { placement } = layoutFor(ctx, buildings, placedBuildings, prestige); + return simulateIsland(placement, ctx).totalPower; +} + /** * Returns the given placements with every derived figure filled in, in the same * order they arrived. A placement on a tile that cannot be built on, or naming diff --git a/src/lib/state/CLAUDE.md b/src/lib/state/CLAUDE.md index 0b4b02f..563fdc8 100644 --- a/src/lib/state/CLAUDE.md +++ b/src/lib/state/CLAUDE.md @@ -1,6 +1,6 @@ # CLAUDE.md — state layer and board rules -Loaded when working under `src/lib/state/`. The six stores and the dependency +Loaded when working under `src/lib/state/`. The seven stores and the dependency DAG between them are summarised in the root `CLAUDE.md`. ## The Time Lab and anomalies: the app side @@ -285,6 +285,43 @@ duration afterwards (`lastRunDurationMs`, `finishedAt`). The solve has a five-minute ceiling, streams its result and shows no progress bar, so without a clock nothing separates "four seconds in" from "about to time out". +### `timelineState` (`timeline.svelte.ts`) + +The game as a whole, for the header's `TimelineStatus`: every island's power at +once, and where the Chronon count stands. **Two figures from two sources, and +keeping them apart is the point.** + +- **`totalPower` is the boards here, live.** The island on screen counts from + its scored placements; every other game island from its saved layout, re-scored + by `refreshIslands` through the simulator's `boardPower` under the current + roster, research and anomaly. That one builds its own island context, because + the simulator's cache holds one board — the one being edited — and walking + eight islands through it would evict it each time. Answers are memoised by + board code and rules, and the board on screen is skipped, since it is re-saved + after every paint. Custom islands and a previewed layout are not counted. +- **`projection` is the game's, run forward.** It is the last import's timeline + carried from `exportedAt` to `now` at `record.energyPerTick` — the power the + game's own boards made, scored at import from the _resolved_ levels rather than + whatever the in-progress mode counted as bought. An edit here changes nothing in + the game, so it must not move the count; a re-import is what reconciles the two. + The formula, the inverse and the jump threshold are the package's + (`data/chronons.ts`); island power is energy **per 3-second tick**, which a live + save confirmed to the second. + +**`record` is the import as the game had it** — `SavedGameImport` under the +`game_import` key. The roster and boards are edited away after an import; this is +what survives, for the tools that need the game's truth: the full research map +(economy and Time Lab, which `configState` never holds), research in progress, +obstacles being cleared, each island's board as a blueprint (the start of a move +list), the export and import times, and the timeline — whose cash (signed: +negative on build credit) and research points are what the cost-aware tools will +read. `uiState.applyGameImport` +writes it through `recordImport`, after the import has landed. A record from a +format version this build cannot read is dropped; the next import rewrites it. + +`now` ticks once a second only while something shows a timeline: +`startClock()` returns its own stop, for a component's `$effect` to hand back. + ### `viewportState` (`viewport.svelte.ts`) The device, from `matchMedia`: `isCompact` (< 1024px — bottom sheet instead of diff --git a/src/lib/state/index.ts b/src/lib/state/index.ts index 6408eee..2554cf7 100755 --- a/src/lib/state/index.ts +++ b/src/lib/state/index.ts @@ -1,5 +1,5 @@ /** - * Six runes singletons, split by what the state *is* rather than which + * Seven runes singletons, split by what the state *is* rather than which * component happens to read it: * * editor — the paintbrush: active tool, selected building @@ -7,6 +7,7 @@ * config — the roster: which components are unlocked, and to what level * solver — the optimizer run: status, streaming result, stop handle * viewport — the device: width class and pointer type, from matchMedia + * timeline — every island's power at once, and the game's Chronon count * ui — the interface: what's open, what's being inspected * * They reference each other directly rather than through events; this app is @@ -70,4 +71,5 @@ export { viewportState } from "./viewport.svelte"; export { layoutState } from "./layout.svelte"; export { configState } from "./config.svelte"; export { solverState } from "./solver.svelte"; +export { timelineState } from "./timeline.svelte"; export { uiState } from "./ui.svelte"; diff --git a/src/lib/state/timeline.svelte.ts b/src/lib/state/timeline.svelte.ts new file mode 100644 index 0000000..419bb5f --- /dev/null +++ b/src/lib/state/timeline.svelte.ts @@ -0,0 +1,252 @@ +import { + ANOMALIES, + BUILDINGS, + CHRONON_REACTOR_ID, + chrononMultiplier, + decodeBlueprint, + encodeBlueprint, + firstEntryBonus, + getAnomaly, + ISLAND_TEMPLATES, + prestigeScales, + projectTimeline, + TICK_SECONDS, + type AnomalyDefinition, + type GameExport, + type PrestigeScales, + type ResolvedGameImport, + type TimelineProjection, +} from "@reactor2/solver"; +import { createPlacement } from "../data/placements"; +import { boardPower } from "../simulation/simulator"; +import { gameImportStorage, type SavedGameImport } from "../storage/storage"; +import { configState } from "./config.svelte"; +import { layoutState } from "./layout.svelte"; + +/** The shipped islands that exist in the game — the ones a total adds up. */ +const GAME_ISLANDS = ISLAND_TEMPLATES.filter((t) => t.game); + +/** + * The player's timeline as a whole: the power of every island at once, and + * where the Chronon count stands. + * + * Two different questions, answered from two different sources, and keeping + * them apart is the point: + * + * - **Power** is the boards *here*, live: the island being edited from its + * scored placements, every other one from its saved layout under the + * current roster, research and anomaly. It moves as the player edits, which + * is what lets them see a change pay before they build it. + * - **Chronons** are the *game's*, projected from the last import: its energy, + * carried forward from the moment of export at the power the game's own + * boards made then. An edit here changes nothing in the game, so it must + * not move the count; a re-import is what brings the two back together. + * + * References `configState` and `layoutState`, and nothing references it but + * `uiState` and the header — so the store graph stays a DAG. + */ +class TimelineState { + /** The last game import, as the game had it. Null before the first. */ + record = $state(gameImportStorage.load()); + + /** Wall clock, epoch ms; `startClock` ticks it while the readout is up. */ + now = $state(Date.now()); + + /** Each island's power from its saved board, keyed by template id. */ + #savedPower = $state>({}); + + /** Power by board and rules, so an unchanged island is not re-scored. */ + #memo = new Map(); + #refreshSeq = 0; + + /** + * The board on screen, live — or null when it is not one the total counts: + * a custom island, or someone else's previewed layout. + */ + get #livePower(): number | null { + if (layoutState.isPreview) return null; + const id = layoutState.activeTemplateId; + if (!GAME_ISLANDS.some((t) => t.id === id)) return null; + let sum = 0; + for (const p of layoutState.placements) sum += p.powerGenerated; + return sum; + } + + /** Every game island's power, per tick, on the boards as they stand here. */ + get totalPower(): number { + const live = this.#livePower; + let sum = 0; + for (const t of GAME_ISLANDS) { + sum += + live !== null && t.id === layoutState.activeTemplateId + ? live + : (this.#savedPower[t.id] ?? 0); + } + return sum; + } + + /** + * Re-scores every island from its saved board. Cheap to call often: a board + * whose code and rules are unchanged is answered from the memo, and a later + * call supersedes one still in flight. + * + * Reads all of its inputs before the first await, so an `$effect` calling it + * tracks exactly the state the answer depends on. + */ + async refreshIslands(): Promise { + const seq = ++this.#refreshSeq; + const upgrades = configState.buildingUpgrades; + const prestige = configState.prestige; + const anomaly = configState.activeAnomaly; + const rules = JSON.stringify([upgrades, configState.prestigeLevels]); + // The board on screen is counted live, and is re-saved after every edit; + // scoring its saved copy too would redo that work on every paint. + const liveId = layoutState.isPreview ? null : layoutState.activeTemplateId; + const boards = GAME_ISLANDS.filter((t) => t.id !== liveId).map((t) => ({ + id: t.id, + code: layoutState.savedGrids[t.id]?.code ?? t.code, + })); + + const next: Record = {}; + for (const { id, code } of boards) { + const key = `${anomaly.id}|${rules}|${code}`; + let power = this.#memo.get(key); + if (power === undefined) { + power = await scoreBoard(code, upgrades, prestige, anomaly); + if (seq !== this.#refreshSeq) return; + this.#memo.set(key, power); + } + next[id] = power; + } + // A memo keyed on whole boards grows with every edit; past a few rounds + // of islands it is cheaper to start again than to track which are live. + if (this.#memo.size > GAME_ISLANDS.length * 8) this.#memo.clear(); + this.#savedPower = next; + } + + /** The Chronon Reactor multiplier the game reported, ×1 without a record. */ + get #multiplier(): number { + return chrononMultiplier(this.record?.research[CHRONON_REACTOR_ID] ?? 0); + } + + /** + * The imported timeline run forward to `now`, or null with no timeline to + * run: nothing imported yet, or a code from before the game wrote one. + */ + get projection(): TimelineProjection | null { + const r = this.record; + if (!r?.timeline) return null; + return projectTimeline( + r.timeline, + r.energyPerTick / TICK_SECONDS, + this.#multiplier, + this.now / 1000, + ); + } + + /** + * The anomalies a jump would still pay the first-entry bonus for — the + * choices a player makes at the jump, so the readout lists them by name. + * One entry per anomaly: a balance variant is the same anomaly. + */ + get unenteredAnomalies(): AnomalyDefinition[] { + const entered = this.record?.timeline?.anomaliesEntered; + if (!entered) return []; + return ANOMALIES.filter( + (a) => + a.id !== "none" && + !a.id.endsWith("_legacy") && + firstEntryBonus(a.id, entered) > 0, + ); + } + + /** + * Keeps `now` ticking once a second, for as long as something shows it. + * Returns the stop, so a component's `$effect` can hand it straight back. + */ + startClock(): () => void { + this.now = Date.now(); + const id = setInterval(() => (this.now = Date.now()), 1000); + return () => clearInterval(id); + } + + /** + * Keeps a game import as the game had it — see `SavedGameImport`. Called by + * `uiState.applyGameImport` once the import has landed. + * + * The power is scored here, from the resolved boards at the resolved + * levels, rather than read back off the islands just written: those are at + * whatever the import mode made of research still running, and the game's + * boards are not running at levels it has not finished. + */ + async recordImport( + exp: GameExport, + resolved: ResolvedGameImport, + ): Promise { + const prestige = prestigeScales(resolved.prestigeLevels); + const anomaly = getAnomaly(resolved.anomalyId); + const islands: Record = {}; + let energyPerTick = 0; + for (const island of resolved.islands) { + islands[island.templateId] = await encodeBlueprint( + island.grid, + island.placements, + ); + energyPerTick += boardPower( + island.grid, + BUILDINGS, + island.placements.map((p) => + createPlacement(p.buildingId, p.x, p.y, resolved.buildingUpgrades), + ), + prestige, + anomaly, + ); + } + + const record: SavedGameImport = { + version: 1, + importedAt: Date.now(), + gameVersion: exp.gameVersion, + anomalyId: exp.anomalyId, + anomalyBalance: exp.anomalyBalance, + research: { ...exp.research }, + researchInProgress: exp.researchInProgress.map((p) => ({ ...p })), + clearing: exp.clearing.map((c) => ({ ...c })), + islands, + lockedTemplateIds: [...resolved.lockedTemplateIds], + energyPerTick, + timeline: exp.timeline + ? { + ...exp.timeline, + anomaliesEntered: [...exp.timeline.anomaliesEntered], + } + : null, + }; + this.record = record; + this.now = Date.now(); + gameImportStorage.save(record); + } +} + +/** One saved board's power under the given rules; 0 if it cannot be read. */ +async function scoreBoard( + code: string, + upgrades: Record, + prestige: PrestigeScales, + anomaly: AnomalyDefinition, +): Promise { + try { + const { grid, placements } = await decodeBlueprint(code); + return boardPower( + grid, + BUILDINGS, + placements.map((p) => createPlacement(p.buildingId, p.x, p.y, upgrades)), + prestige, + anomaly, + ); + } catch { + return 0; + } +} + +export const timelineState = new TimelineState(); diff --git a/src/lib/state/timeline.test.ts b/src/lib/state/timeline.test.ts new file mode 100644 index 0000000..53864e0 --- /dev/null +++ b/src/lib/state/timeline.test.ts @@ -0,0 +1,165 @@ +/** + * What the header's timeline readout is built on: an import kept as the game + * had it, every island's power added up, and the Chronon count run forward + * from the moment of export. + * + * The package pins the formula; these pin the app's two promises about it. + * The count runs at the power the *game's* boards made, not at a board edited + * here since. And the total is the boards *here*, live. + */ +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { beforeEach, describe, expect, it } from "vitest"; + +// The storage helpers are SSR-guarded on `typeof window`, so a test running in +// node needs both a window and a localStorage before it imports anything that +// touches them. +const store = new Map(); +(globalThis as { window?: unknown }).window = globalThis; +(globalThis as { localStorage?: unknown }).localStorage = { + getItem: (key: string) => (store.has(key) ? store.get(key)! : null), + setItem: (key: string, value: string) => void store.set(key, String(value)), + removeItem: (key: string) => void store.delete(key), + clear: () => store.clear(), +}; + +const { decodeGameExport, resolveGameExport, applyInProgress, TICK_SECONDS } = + await import("@reactor2/solver"); +const { configState } = await import("./config.svelte"); +const { layoutState } = await import("./layout.svelte"); +const { timelineState } = await import("./timeline.svelte"); +const { gameImportStorage } = await import("../storage/storage"); + +const FIXTURES = join( + dirname(fileURLToPath(import.meta.url)), + "../../../packages/solver/tests/gameExports", +); + +async function fixture(name: string) { + const exp = await decodeGameExport( + readFileSync(join(FIXTURES, `${name}.txt`), "utf8"), + ); + return { exp, resolved: await resolveGameExport(exp) }; +} + +/** Imports a fixture the way `uiState.applyGameImport` does. */ +async function importFixture(name: string) { + const { exp, resolved } = await fixture(name); + const state = applyInProgress(resolved, "ignore"); + configState.applyGameImport(state, resolved.anomalyId); + layoutState.setPrestige(configState.prestige); + layoutState.setAnomaly(configState.activeAnomaly); + await layoutState.importGameIslands( + resolved.islands, + configState.buildingUpgrades, + resolved.lockedTemplateIds, + ); + await timelineState.recordImport(exp, resolved); + return { exp, resolved }; +} + +describe("the timeline", () => { + beforeEach(async () => { + store.clear(); + timelineState.record = null; + layoutState.savedGrids = {}; + layoutState.customIslands = []; + layoutState.activeTemplateId = "island1"; + await layoutState.exitPreview({}); + await layoutState.hydrate({}); + }); + + it("keeps the import as the game had it, and survives a reload", async () => { + const { exp, resolved } = await importFixture("gen2_cryo_city34"); + const r = timelineState.record!; + + expect(r.gameVersion).toBe("1.1.11"); + expect(r.timeline).toEqual(exp.timeline); + // The economy research the roster never held is all there. + expect(r.research).toEqual(exp.research); + expect(Object.keys(r.islands).sort()).toEqual( + resolved.islands.map((i) => i.templateId).sort(), + ); + expect(r.energyPerTick).toBeGreaterThan(0); + expect(gameImportStorage.load()).toEqual(r); + }); + + it("projects the game's own award at the moment of export", async () => { + const { exp } = await importFixture("gen1_cryo_city41"); + timelineState.now = exp.timeline!.exportedAt * 1000; + expect(timelineState.projection).toMatchObject({ + sinceExport: 0, + award: exp.timeline!.jumpAward, + canJump: true, + }); + }); + + it("runs energy forward at the game boards' power, per tick", async () => { + const { exp } = await importFixture("gen2_singularity_city32"); + const r = timelineState.record!; + timelineState.now = (exp.timeline!.exportedAt + 600) * 1000; + expect(timelineState.projection!.energy).toBeCloseTo( + exp.timeline!.energy + (r.energyPerTick / TICK_SECONDS) * 600, + -10, + ); + }); + + /* + * The game's own rate, measured: this player's save was exported more than + * once, with the same boards and research and only offline time between. + * The first export's energy was 1.777171287713242e31 at 1119984 s; the + * fixture is a later one, 23,897 s on. What the game added in between, over + * the time between, is the rate — and the simulator, through the 3-second + * tick, has to land on it. It does, to 66 parts per million. + */ + it("projects at the rate the game itself measured on a real save", async () => { + const { exp } = await importFixture("gen2_city52_9c43e4b7"); + const t = exp.timeline!; + const measured = + (t.energy - 1.777171287713242e31) / (t.elapsedSeconds - 1119984); + const ours = timelineState.record!.energyPerTick / TICK_SECONDS; + expect(Math.abs(ours / measured - 1)).toBeLessThan(1e-4); + }); + + it("does not move the count when a board here is edited", async () => { + await importFixture("gen2_cryo_city34"); + const before = timelineState.record!.energyPerTick; + layoutState.placements = []; + expect(timelineState.record!.energyPerTick).toBe(before); + }); + + it("adds every island up to the game's power when nothing was changed", async () => { + await importFixture("gen2_cryo_city34"); + await timelineState.refreshIslands(); + const game = timelineState.record!.energyPerTick; + expect(timelineState.totalPower).toBeCloseTo(game, -Math.log10(game) + 9); + }); + + it("follows the board on screen live", async () => { + await importFixture("gen2_cryo_city34"); + await timelineState.refreshIslands(); + const total = timelineState.totalPower; + const here = layoutState.placements.reduce( + (s, p) => s + p.powerGenerated, + 0, + ); + expect(here).toBeGreaterThan(0); + layoutState.placements = []; + expect(timelineState.totalPower).toBeCloseTo(total - here, -20); + }); + + it("lists the anomalies a jump would still pay the bonus for", async () => { + await importFixture("gen2_cryo_city34"); + expect(timelineState.unenteredAnomalies.map((a) => a.id)).toEqual([ + "singularity_isolation", + ]); + }); + + it("has no projection for a code from before the timeline section", async () => { + await importFixture("city34-timeline3"); + expect(timelineState.record!.timeline).toBeNull(); + expect(timelineState.projection).toBeNull(); + expect(timelineState.unenteredAnomalies).toEqual([]); + }); +}); diff --git a/src/lib/state/ui.svelte.ts b/src/lib/state/ui.svelte.ts index 78035de..cc08521 100755 --- a/src/lib/state/ui.svelte.ts +++ b/src/lib/state/ui.svelte.ts @@ -10,6 +10,7 @@ import { formatNumberForFilename, isGameExportCode, resolveGameExport, + type GameExport, type InProgressMode, type ResolvedGameImport, } from "@reactor2/solver"; @@ -24,6 +25,7 @@ import { evaluatePlan, type PlanReport } from "../simulation/upgradePlan"; import { configState } from "./config.svelte"; import { layoutState } from "./layout.svelte"; import { solverState } from "./solver.svelte"; +import { timelineState } from "./timeline.svelte"; import { viewportState } from "./viewport.svelte"; /** A tile the inspector can point at. Internal — nothing outside builds one. */ @@ -455,6 +457,12 @@ class UIState { * asking to replace anything. Null for anything else in the box. */ gameImport = $state(null); + /** + * The same code as the game wrote it. The resolver translates what a board + * needs and drops the rest — the economy research, the timeline — which + * `timelineState.recordImport` keeps. + */ + #gameExport: GameExport | null = null; /** What the import does with research still running in the game. */ gameImportMode = $state("plan"); /** Orders reads of the box, so a slow decode cannot land over a newer paste. */ @@ -1042,6 +1050,7 @@ class UIState { this.importError = null; this.isImporting = false; this.gameImport = null; + this.#gameExport = null; this.activeModal = "import"; } @@ -1054,16 +1063,20 @@ class UIState { const seq = ++this.#gameReadSeq; if (!isGameExportCode(code)) { this.gameImport = null; + this.#gameExport = null; return; } try { - const resolved = await resolveGameExport(await decodeGameExport(code)); + const exp = await decodeGameExport(code); + const resolved = await resolveGameExport(exp); if (seq !== this.#gameReadSeq) return; + this.#gameExport = exp; this.gameImport = resolved; this.importError = null; } catch (err) { if (seq !== this.#gameReadSeq) return; this.gameImport = null; + this.#gameExport = null; this.importError = err instanceof Error ? err.message : "That code could not be read."; } @@ -1080,7 +1093,8 @@ class UIState { */ async applyGameImport() { const resolved = this.gameImport; - if (!resolved || this.isImporting) return; + const exp = this.#gameExport; + if (!resolved || !exp || this.isImporting) return; this.isImporting = true; this.importError = null; try { @@ -1099,9 +1113,11 @@ class UIState { // Every stored solve was found under the old roster: keep each one the // import left buildable, re-scored, before restore() reads the store. await solverState.carryOverSolves(resolved.lockedTemplateIds); + await timelineState.recordImport(exp, resolved); this.activeModal = null; this.importCode = ""; this.gameImport = null; + this.#gameExport = null; solverState.restore(); this.closeInspector(); this.recenterCanvas(); diff --git a/src/lib/storage/storage.ts b/src/lib/storage/storage.ts index 1f4c7ab..884c273 100755 --- a/src/lib/storage/storage.ts +++ b/src/lib/storage/storage.ts @@ -5,6 +5,9 @@ import { DEFAULT_ANOMALY_ID, MAX_UPGRADE_STEPS, type AnomalyId, + type GameExportClearing, + type GameExportProgress, + type GameExportTimeline, type OptimizationResult, type UpgradeStep, } from "@reactor2/solver"; @@ -29,6 +32,7 @@ const KEYS = { UPGRADE_PLAN: "upgrade_plan", UI: "ui_prefs", SOLVE: "solver_result", + GAME_IMPORT: "game_import", } as const; export interface UiPrefs { @@ -355,6 +359,57 @@ export const solverStorage = { }, }; +/** + * The last game code the player imported, kept as the game had it. + * + * An import is applied and then edited away: the roster follows the next tier + * the player clicks, the boards follow every paint. What the game actually + * said survives only here, and that is what the timeline readout and the + * planned tools need — a Chronon projection runs forward from the export's own + * figures at the power the *game's* boards made, a move list starts from the + * board the player really has, and a spending planner needs the economy + * research that `configState` never held. + * + * Bumped `version` rather than a migration when the shape changes: a record + * this build cannot read is dropped and the next import rewrites it, since the + * game is the source of every figure in it. + */ +export interface SavedGameImport { + version: 1; + /** When the player imported it, epoch ms on this device. */ + importedAt: number; + gameVersion: string; + /** The header's anomaly, the game's id (`tidal_ascendancy_legacy` stays). */ + anomalyId: string; + anomalyBalance: number; + /** Every research node by the game's id, economy and Time Lab included. */ + research: Record; + researchInProgress: GameExportProgress[]; + clearing: GameExportClearing[]; + /** Template id -> blueprint of that island's board as the game had it. */ + islands: Record; + /** Islands still locked in the game. */ + lockedTemplateIds: string[]; + /** + * The game boards' power, all islands, per tick — at the tiers, research + * and anomaly the game ran them at, not the ones an in-progress import may + * have counted as bought. The rate a projection runs forward at. + */ + energyPerTick: number; + /** Section 7; null on a code from before game 1.1.11. */ + timeline: GameExportTimeline | null; +} + +const GAME_IMPORT_VERSION = 1; + +export const gameImportStorage = { + load: (): SavedGameImport | null => { + const raw = getItem(KEYS.GAME_IMPORT, null); + return raw && raw.version === GAME_IMPORT_VERSION ? raw : null; + }, + save: (data: SavedGameImport): void => setItem(KEYS.GAME_IMPORT, data), +}; + export const gridStorage = { loadGridState: (): StoragePayload | null => getItem(KEYS.GRID_STATE, null), diff --git a/src/lib/utils/formatters.ts b/src/lib/utils/formatters.ts index 58226fd..e33f1ee 100755 --- a/src/lib/utils/formatters.ts +++ b/src/lib/utils/formatters.ts @@ -45,6 +45,23 @@ export function formatTimeAgo( return `${Math.floor(seconds / 86400)}d ago`; } +/** + * A span of game time, to its two largest units: "13d 4h", "4h 17m", + * "4m 02s", "37s". For timeline lengths and countdowns, where the game itself + * reads in days and hours and a countdown in minutes needs its seconds. + */ +export function formatSpan(seconds: number): string { + const s = Math.max(0, Math.floor(seconds)); + const d = Math.floor(s / 86400); + const h = Math.floor((s % 86400) / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + if (d > 0) return `${d}d ${h}h`; + if (h > 0) return `${h}h ${m}m`; + if (m > 0) return `${m}m ${sec.toString().padStart(2, "0")}s`; + return `${sec}s`; +} + // --------------------------------------------------------------------------- // Tile coordinates // --------------------------------------------------------------------------- From c36bd144db71a6579763ec0e46a089766b462e98 Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:10:00 +0300 Subject: [PATCH 4/9] Draw heat and cooling links from the inspected building Hovering a building, or pinning one on touch, draws dashed lines along the ground to every building it actually exchanged heat or cooling with, the dashes marching from supplier to receiver. The pairs come from the scorer's own distribution (simulateIsland gains an optional, read-only flows output), so an idle reactor beside a full generator gets no line. A Settings switch, "Follow connections" (on by default), carries the lines on through linked buildings so the whole network shows, fainter past the first step. The layer is hidden while the board is exported as an image. --- packages/solver/src/solver/simulate.ts | 54 ++++++++ src/lib/components/canvas/PixiCanvas.svelte | 38 +++++- .../components/modals/SettingsModal.svelte | 26 ++++ src/lib/pixi/gridPainter.ts | 127 +++++++++++++++++- src/lib/simulation/simulator.test.ts | 81 +++++++++++ src/lib/simulation/simulator.ts | 91 +++++++++++++ src/lib/state/ui.svelte.ts | 17 +++ src/lib/storage/storage.ts | 8 ++ 8 files changed, 440 insertions(+), 2 deletions(-) diff --git a/packages/solver/src/solver/simulate.ts b/packages/solver/src/solver/simulate.ts index 99dfa4b..2add9a4 100755 --- a/packages/solver/src/solver/simulate.ts +++ b/packages/solver/src/solver/simulate.ts @@ -64,11 +64,19 @@ const conversion = { power: 0.0, waste: 0.0 }; * its reactors and generators are moving around, which is what the inspector * asks for. It changes no number that a short-circuited layout would otherwise * have reported; it only fills in the ones the search would have skipped. + * + * `flows`, when given, is filled with every supplier -> consumer pair that + * actually moved something, as flat `[supplierTile, consumerTile, ...]` island + * tile indices: heat from reactors to generators, then cooling from coolers to + * power sources. It is a read of what the distribution already decided — it + * changes no number — and the search never asks for it, so the hot path pays + * one untaken branch per distribution. */ export function simulateIsland( placement: Placement, ctx: IslandContext, fullReport = false, + flows?: number[], ): SimulationResult { const n = ctx.n; const reactorTiles = ctx.reactorTiles; @@ -189,6 +197,16 @@ export function simulateIsland( numGenerators, ctx, ); + if (flows) { + collectFlows( + ctx, + flows, + reactorTiles, + numReactors, + generatorTiles, + numGenerators, + ); + } for (let i = 0; i < numReactors; i++) heatOut[reactorTiles[i]] = d.supplierSent[i]; for (let j = 0; j < numGenerators; j++) @@ -281,6 +299,17 @@ export function simulateIsland( for (let i = 0; i < numCoolers; i++) heatOut[coolerTiles[i]] = layout[coolerTiles[i]]!.effectiveValue * share; + + // Every cooler doing work pays into every source the pool served. + if (flows) { + for (let i = 0; i < numCoolers; i++) { + if (heatOut[coolerTiles[i]] <= EPS) continue; + for (let j = 0; j < numWaste; j++) { + if (coolingIn[wasteTiles[j]] > EPS) + flows.push(coolerTiles[i], wasteTiles[j]); + } + } + } } else { for (let i = 0; i < numCoolers; i++) { d.supplierCap[i] = layout[coolerTiles[i]]!.effectiveValue; @@ -289,6 +318,9 @@ export function simulateIsland( d.consumerCap[j] = wasteOf[wasteTiles[j]]; } runDistribution(coolerTiles, numCoolers, wasteTiles, numWaste, ctx); + if (flows) { + collectFlows(ctx, flows, coolerTiles, numCoolers, wasteTiles, numWaste); + } for (let i = 0; i < numCoolers; i++) heatOut[coolerTiles[i]] = d.supplierSent[i]; for (let j = 0; j < numWaste; j++) @@ -337,6 +369,28 @@ export function simulateIsland( return { totalPower, placements }; } +/** + * Appends every pair the last `runDistribution` moved something along — see + * `simulateIsland`'s `flows`. Module-level rather than a closure so the search, + * which never passes `flows`, allocates nothing for it. + */ +function collectFlows( + ctx: IslandContext, + flows: number[], + supplierTiles: Int32Array, + numSuppliers: number, + consumerTiles: Int32Array, + numConsumers: number, +): void { + const flow = ctx.dist.flow; + for (let i = 0; i < numSuppliers; i++) { + for (let j = 0; j < numConsumers; j++) { + if (flow[i * numConsumers + j] > EPS) + flows.push(supplierTiles[i], consumerTiles[j]); + } + } +} + /** * Report rows for a layout that produces nothing — every measured field is * zero, leaving each building's two capacity figures (`baseValue` and the diff --git a/src/lib/components/canvas/PixiCanvas.svelte b/src/lib/components/canvas/PixiCanvas.svelte index ac9f5f7..8ded279 100755 --- a/src/lib/components/canvas/PixiCanvas.svelte +++ b/src/lib/components/canvas/PixiCanvas.svelte @@ -13,7 +13,12 @@ placementFillPercent, } from "../../data/placements"; import { BUILDINGS, findBuilding } from "@reactor2/solver"; - import { ratedPlacements, ratingShifts } from "../../simulation/simulator"; + import { + linksFrom, + placementFlows, + ratedPlacements, + ratingShifts, + } from "../../simulation/simulator"; import { anomalyIconFor, STATE_ICON } from "../../data/boardIcons"; import type { BuildingOverlay } from "../../pixi/gridPainter"; import { onMount, onDestroy, untrack } from "svelte"; @@ -346,6 +351,8 @@ const longest = Math.max(frame.width, frame.height); const resolution = Math.min(scale, EXPORT_MAX_SIDE_PX / longest); + // The inspected building's partner lines are a pointer's, not the board's. + gridRenderer?.setLinksVisible(false); const canvas = app.renderer.extract.canvas({ target: gridContainer, frame, @@ -355,6 +362,7 @@ // than a transparent halo that turns black in most image viewers. clearColor: CANVAS_CLEAR, }); + gridRenderer?.setLinksVisible(true); // `ICanvas` is Pixi's abstraction over an HTMLCanvasElement and an // OffscreenCanvas, which spell "give me a blob" differently. @@ -803,6 +811,34 @@ viewportControls?.setAnimated(on); }); + /* + * What moved between buildings on the board on screen, off the same scorer + * the overlays read. Only re-run when the board changes, not on hover. + */ + let boardFlows = $derived( + placementFlows( + layoutState.grid, + BUILDINGS, + uiState.visiblePlacements, + layoutState.placementPrestige, + layoutState.placementAnomaly, + ), + ); + + /* + * Lines from the inspected building — hovered on a mouse, pinned on touch, + * which `inspectedTile` already decides — to every building it sends heat or + * cooling to or takes it from, and on through theirs with `chainLinks`. Only + * a building standing on the tile has flows: hovering grass draws nothing. + */ + $effect(() => { + const focus = uiState.inspectedTile; + const flows = boardFlows; + const chain = uiState.chainLinks; + if (!isAtlasLoaded) return; + gridRenderer?.setLinks(focus ? linksFrom(flows, focus, chain) : []); + }); + /* * One re-frame once the chrome has measured itself. * diff --git a/src/lib/components/modals/SettingsModal.svelte b/src/lib/components/modals/SettingsModal.svelte index eb80bcd..b7c011d 100755 --- a/src/lib/components/modals/SettingsModal.svelte +++ b/src/lib/components/modals/SettingsModal.svelte @@ -6,6 +6,7 @@ ImageDown, Sparkles, Vibrate, + Waypoints, } from "lucide-svelte"; import type { ImageScale } from "../../types/ui"; import { EXPORT_MAX_SIDE_PX } from "../../pixi/boardExport"; @@ -62,6 +63,12 @@ : "Building figures stay in the readout; tap a building to see them.", ); + let chainLinksHint = $derived( + uiState.chainLinks + ? "Lines follow on from a building to everything it is connected to." + : "Lines reach only the buildings next in line to the one you point at.", + ); + /* * Says what is collected rather than what the switch is called: "analytics" * alone invites the reader to assume the worst. The first branch does the @@ -145,6 +152,25 @@
+
+ + + + Follow connections + {chainLinksHint} + + + +
+
diff --git a/src/lib/pixi/gridPainter.ts b/src/lib/pixi/gridPainter.ts index c4f8c67..d6f43a0 100755 --- a/src/lib/pixi/gridPainter.ts +++ b/src/lib/pixi/gridPainter.ts @@ -19,6 +19,7 @@ import { createScaledSprite, } from "./atlas"; import { placementStatus, type PlacementStatus } from "../data/placements"; +import type { BoardLink } from "../simulation/simulator"; import { pulseAlpha, STATUS_PULSE, type Pulse } from "./statusPulse"; import { createStatusBadge } from "./statusBadge"; import { createIconSprite } from "./atlas"; @@ -104,6 +105,33 @@ const STATUS_FRAME: Record = { idle: FRAME_KEYS.indicatorIdle, }; +/** + * The lines from the inspected building to the ones it works with, drawn the + * way the game draws its own: a dashed line along the ground, in the board's + * "this is selected" cyan, on a dark track so it still reads across grass. + * + * The dashes march from supplier to receiver at `LINK_SPEED` world px/s, so the + * line says which way the heat or cooling goes without a label. With animation + * off they stand still and the line is simply a line. + */ +const LINK_DASH = 12; +const LINK_GAP = 9; +const LINK_SPEED = 28; +const LINK_WIDTH = 4; +/** + * The dark band the dashes run along. Cyan alone has almost no contrast with + * the grass and the green and amber status pads it crosses, so the line sat + * invisible beside exactly the buildings with something to say; a dark track + * under it reads on every ground the board has. + */ +const LINK_TRACK_WIDTH = 10; +const LINK_TRACK = 0x0b1f3a; +/** + * How strongly a link further out along the chain draws against one touching + * the focus — see `uiState.chainLinks`. Visible, but a step behind. + */ +const LINK_CHAIN_STRENGTH = 0.75; + /** A building sprite that breathes, and the shape of its breath. */ interface PulsingSprite { sprite: Sprite; @@ -214,6 +242,11 @@ export class GridRenderer { private hoverHighlight: Graphics; + /** See `setLinks`. Its own layer, so `clear()` never touches it. */ + private linkGraphics: Graphics; + private links: BoardLink[] = []; + private linkKey = ""; + private islandTileNodes: (Container | null)[][] = []; private gridTileNodes: (Container | null)[][] = []; private propTileNodes: (Container | null)[][] = []; @@ -287,6 +320,10 @@ export class GridRenderer { // then props, then badges, then ghosts on top of everything. this.gridContainer.addChild(this.islandContainer); this.gridContainer.addChild(this.gridLinesContainer); + // Partner lines lie on the ground: over the pads, under the buildings. + this.linkGraphics = new Graphics(); + this.linkGraphics.eventMode = "none"; + this.gridContainer.addChild(this.linkGraphics); this.gridContainer.addChild(this.propsContainer); this.gridContainer.addChild(this.badgeContainer); this.gridContainer.addChild(this.ghostContainer); @@ -308,6 +345,7 @@ export class GridRenderer { public destroy(): void { this.clear(); this.hoverHighlight.destroy({ children: true }); + this.linkGraphics.destroy(); this.islandContainer.destroy({ children: true }); this.gridLinesContainer.destroy({ children: true }); this.propsContainer.destroy({ children: true }); @@ -649,7 +687,9 @@ export class GridRenderer { * The curve itself is `pulseAlpha`; this is the walk that applies it. */ public tick(elapsedMs: number): void { - if (!this.animate || this.pulsing.size === 0) return; + if (!this.animate) return; + if (this.links.length > 0) this.drawLinks(elapsedMs); + if (this.pulsing.size === 0) return; for (const { sprite, pulse } of this.pulsing.values()) { if (sprite.destroyed) continue; @@ -674,6 +714,7 @@ export class GridRenderer { this.animate = on; if (on) return; + this.drawLinks(0); for (const { sprite, pulse } of this.pulsing.values()) { if (!sprite.destroyed) sprite.alpha = pulse.minAlpha; } @@ -732,6 +773,90 @@ export class GridRenderer { this.ghostContainer.sortChildren(); } + /** + * Shows the lines from the inspected building to its partners, or none. + * + * Pushed in by `PixiCanvas`, which reads them off the scorer — the painter + * only draws. Skipped when the set has not changed, since the effect that pushes + * it re-runs on every board repaint. + */ + public setLinks(links: BoardLink[]): void { + const key = links + .map( + (l) => + `${l.from.x},${l.from.y}>${l.to.x},${l.to.y}${l.direct ? "!" : ""}`, + ) + .join("|"); + if (key === this.linkKey) return; + this.linkKey = key; + this.links = links; + this.drawLinks(0); + } + + /** + * Hides or shows the partner lines without forgetting them — for the board's + * image export, which renders this container and must not carry a pointer's + * passing interest into a picture meant for someone else. + */ + public setLinksVisible(on: boolean): void { + this.linkGraphics.visible = on; + } + + /** Redraws every partner line with its dashes advanced to `elapsedMs`. */ + private drawLinks(elapsedMs: number): void { + const g = this.linkGraphics; + g.clear(); + if (this.links.length === 0) return; + + const period = LINK_DASH + LINK_GAP; + const phase = ((elapsedMs / 1000) * LINK_SPEED) % period; + + // The chain first and fainter, so the focus's own partners draw over it + // and still read as the answer to "what does this one touch". + for (const direct of [false, true]) { + const group = this.links.filter((l) => l.direct === direct); + if (group.length === 0) continue; + const strength = direct ? 1 : LINK_CHAIN_STRENGTH; + + for (const { from, to } of group) { + const a = gridToIso(from.x, from.y); + const b = gridToIso(to.x, to.y); + g.moveTo(a.x, a.y).lineTo(b.x, b.y); + } + g.stroke({ + width: LINK_TRACK_WIDTH, + color: LINK_TRACK, + alpha: 0.85 * strength, + cap: "round", + }); + + for (const { from, to } of group) { + const a = gridToIso(from.x, from.y); + const b = gridToIso(to.x, to.y); + const length = Math.hypot(b.x - a.x, b.y - a.y); + if (length === 0) continue; + const ux = (b.x - a.x) / length; + const uy = (b.y - a.y) / length; + // Starts one period back so the first dash slides in from the supplier. + for (let t = phase - period; t < length; t += period) { + const start = Math.max(t, 0); + const end = Math.min(t + LINK_DASH, length); + if (end <= start) continue; + g.moveTo(a.x + ux * start, a.y + uy * start).lineTo( + a.x + ux * end, + a.y + uy * end, + ); + } + } + g.stroke({ + width: LINK_WIDTH, + color: ACCENT, + alpha: 0.95 * strength, + cap: "round", + }); + } + } + public setHover(x: number | null, y: number | null): void { if (x === null || y === null) { this.hoverHighlight.visible = false; diff --git a/src/lib/simulation/simulator.test.ts b/src/lib/simulation/simulator.test.ts index e7c1393..0271b70 100755 --- a/src/lib/simulation/simulator.test.ts +++ b/src/lib/simulation/simulator.test.ts @@ -24,6 +24,8 @@ */ import { describe, it, expect } from "vitest"; import { + linksFrom, + placementFlows, ratedPlacementAt, ratingShifts, simulatePlacedBuildings, @@ -684,3 +686,82 @@ describe("a rating shift marks exactly the buildings the rules moved", () => { expect(shiftsOf(walledGrid(5, 3), spec, CRYO)).toEqual([null, "down"]); }); }); + +describe("a flow is drawn only where something moved", () => { + const pairsOf = (spec: Spec, anomaly?: AnomalyDefinition, w = 8, h = 8) => + placementFlows(grassGrid(w, h), DEFS, place(spec), undefined, anomaly) + .map((f) => `${f.from.x},${f.from.y}>${f.to.x},${f.to.y}`) + .sort(); + + /* + * One generator between two reactors and two coolers. The game walks columns + * left to right, and within one bottom-up: the left reactor fills the + * generator on its own, so the right one sleeps beside it; the lower cooler + * covers all its waste, so the upper one has nothing to do. + */ + const contested: Spec = [ + [0, 1, "reactor", VALUES.reactor], + [2, 1, "reactor", VALUES.reactor], + [1, 1, "generator", VALUES.generator], + [1, 2, "cooler", VALUES.cooler], + [1, 0, "cooler", VALUES.cooler], + ]; + + it("links a generator to the reactor and cooler that served it, not the idle ones beside it", () => { + expect(pairsOf(contested)).toEqual(["0,1>1,1", "1,2>1,1"]); + }); + + it("links nothing to a reactor with no generator in reach", () => { + expect( + pairsOf([ + [0, 0, "reactor", VALUES.reactor], + [3, 3, "generator", VALUES.generator], + ]), + ).toEqual([]); + }); + + it("feeds every source from every working cooler under Cryo Nexus", () => { + const far: Spec = [...contested, [6, 6, "cooler", VALUES.cooler]]; + expect(pairsOf(far, getAnomaly("cryo_nexus"))).toEqual([ + "0,1>1,1", + "1,0>1,1", + "1,2>1,1", + "6,6>1,1", + ]); + }); +}); + +describe("the links drawn from a building", () => { + const flow = (a: [number, number], b: [number, number]) => ({ + from: { x: a[0], y: a[1] }, + to: { x: b[0], y: b[1] }, + }); + // Reactor (0,0) -> generator (1,0) <- cooler (2,0); generator (1,0) is also + // fed by reactor (1,1), and a separate pair (5,5) -> (6,5) shares nothing. + const flows = [ + flow([0, 0], [1, 0]), + flow([2, 0], [1, 0]), + flow([1, 1], [1, 0]), + flow([5, 5], [6, 5]), + ]; + const drawn = (focus: [number, number], chain: boolean) => + linksFrom(flows, { x: focus[0], y: focus[1] }, chain) + .map( + (l) => + `${l.from.x},${l.from.y}>${l.to.x},${l.to.y}${l.direct ? "" : "~"}`, + ) + .sort(); + + it("draws only the focus's own flows without the chain", () => { + expect(drawn([0, 0], false)).toEqual(["0,0>1,0"]); + }); + + it("follows the chain through linked buildings, fainter past the first step", () => { + expect(drawn([0, 0], true)).toEqual(["0,0>1,0", "1,1>1,0~", "2,0>1,0~"]); + }); + + it("never reaches a network the focus is not part of", () => { + expect(drawn([5, 5], true)).toEqual(["5,5>6,5"]); + expect(drawn([9, 9], true)).toEqual([]); + }); +}); diff --git a/src/lib/simulation/simulator.ts b/src/lib/simulation/simulator.ts index 0154eed..5c68e0d 100755 --- a/src/lib/simulation/simulator.ts +++ b/src/lib/simulation/simulator.ts @@ -244,6 +244,97 @@ export function simulatePlacedBuildings( return results; } +/** One line on the board: `from` supplies `to`, both as tile coordinates. */ +export interface Flow { + from: { x: number; y: number }; + to: { x: number; y: number }; +} + +/** A `Flow` as the board draws it: `direct` when it touches the focus itself. */ +export interface BoardLink extends Flow { + direct: boolean; +} + +/** + * The flows to draw for the building on `focus`: the ones touching it, and + * with `chain` every flow reachable from it through linked buildings — the + * whole network it is part of, so a reactor shows the coolers that keep its + * generators running. Direction is ignored for reach (a generator's cooler is + * as much part of the reactor's chain as the generator), and each flow appears + * once. + */ +export function linksFrom( + flows: readonly Flow[], + focus: { x: number; y: number }, + chain: boolean, +): BoardLink[] { + const key = (p: { x: number; y: number }) => `${p.x},${p.y}`; + const start = key(focus); + const reached = new Set([start]); + const queue = [start]; + const taken = new Set(); + const links: BoardLink[] = []; + + while (queue.length > 0) { + const at = queue.shift()!; + flows.forEach((f, i) => { + if (taken.has(i)) return; + const a = key(f.from); + const b = key(f.to); + if (a !== at && b !== at) return; + taken.add(i); + links.push({ ...f, direct: at === start }); + if (!chain) return; + for (const next of [a, b]) { + if (reached.has(next)) continue; + reached.add(next); + queue.push(next); + } + }); + } + return links; +} + +/** + * Every pair of buildings on the board that actually moved something on the + * last tick: a reactor's heat into a generator, a cooler's cooling into a power + * source. The board draws the ones touching the building under the pointer. + * + * Read off the same distribution that scores the board, not re-derived from + * adjacency, because being *beside* a partner is not using it: a reactor whose + * generators are already full sends nothing, and neither does a cooler beside a + * source another cooler has covered. Under Cryo Nexus every working cooler + * feeds every source the pool served, which is what the pool does. + */ +export function placementFlows( + grid: Tile[][], + buildings: readonly BuildingDefinition[], + placedBuildings: PlacedBuilding[], + prestige?: PrestigeScales, + anomaly: AnomalyDefinition = getAnomaly(undefined), +): Flow[] { + if (!grid?.length || !grid[0]?.length || placedBuildings.length === 0) { + return []; + } + const ctx = contextFor(grid, anomaly); + if (ctx.n === 0) return []; + + const { placement } = layoutFor(ctx, buildings, placedBuildings, prestige); + const pairs: number[] = []; + simulateIsland(placement, ctx, true, pairs); + + const flows: Flow[] = []; + for (let k = 0; k < pairs.length; k += 2) { + const a = pairs[k]; + const b = pairs[k + 1]; + flows.push({ + from: { x: ctx.xs[a], y: ctx.ys[a] }, + to: { x: ctx.xs[b], y: ctx.ys[b] }, + }); + } + return flows; +} + /** * What the building on `(x, y)` was **rated for** on the board around it: the * three ceilings every figure in its scored row was measured against. Null on a diff --git a/src/lib/state/ui.svelte.ts b/src/lib/state/ui.svelte.ts index cc08521..dba9b36 100755 --- a/src/lib/state/ui.svelte.ts +++ b/src/lib/state/ui.svelte.ts @@ -307,6 +307,23 @@ class UIState { uiStorage.savePrefs({ fillBadges: on }); } + /** + * Whether the inspected building's lines carry on outward — through the + * buildings it is linked to, and theirs, until the network it belongs to is + * drawn whole. Off, only its own partners are linked. + */ + #chainLinks = $state(uiStorage.loadPrefs().chainLinks); + + get chainLinks(): boolean { + return this.#chainLinks; + } + + setChainLinks(on: boolean) { + if (this.#chainLinks === on) return; + this.#chainLinks = on; + uiStorage.savePrefs({ chainLinks: on }); + } + /** * Whether usage collection is off, or `null` for "follow the browser". * diff --git a/src/lib/storage/storage.ts b/src/lib/storage/storage.ts index 884c273..47c1b52 100755 --- a/src/lib/storage/storage.ts +++ b/src/lib/storage/storage.ts @@ -82,6 +82,13 @@ export interface UiPrefs { * one place the board says how hard each building is working without a tap. */ fillBadges: boolean; + /** + * Whether the lines from an inspected building carry on through the buildings + * it is linked to — see `uiState.chainLinks`. On by default: a reactor's + * heat is only worth anything once the generator's coolers take its waste, + * and the whole chain is what answers "what does this one do for me". + */ + chainLinks: boolean; /** * Whether usage collection is switched **off** — see * `uiState.analyticsDisabled`. The negative, because gtag's own switch is @@ -102,6 +109,7 @@ const DEFAULT_UI_PREFS: UiPrefs = { solveMode: DEFAULT_SOLVE_MODE, haptics: true, fillBadges: true, + chainLinks: true, imageScale: 1, }; From f1ea47e366f4a3eda7226ee4395e5283ed2cdbe3 Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:24:46 +0300 Subject: [PATCH 5/9] Count down to a target Chronon award, and lead the panel with the reward The timeline panel opens on what a jump would pay now, with the game's own bar toward the next Chronon ("Next in 2m 30s of 4m 41s"), and keeps everything else to a line: power with the game's figure beside it when the boards here differ, Chronons held, the timeline's length. - Target: type the award you are waiting for, or tap a chip sized to today's award (11,483 gives 12k, 15k, 20k; 723 gives 730, 750, 800). It shows how long until the game pays it, the clock time, and what you would hold after the jump, with the +88 while an anomaly is unentered. An empty field reads today's award. The field is bare digits while focused, comma-grouped after, and live as it is typed. A new import clears the target. A target more than a year out says so. - Pace: Chronons an hour now against this timeline's average. Every Chronon takes longer than the last, so once the first falls below the second a fresh timeline like this one would earn faster. - With solves: every island with its stored solve built, re-scored under today's roster, and how much sooner the target lands if the game ran them. A solve weaker than its board is ignored. data/chronons.ts gains secondsUntilAward and the projection's progress toward and length of the Chronon under way. The game's slow ticks are neither modelled nor mentioned. --- packages/solver/src/data/chronons.ts | 34 ++ packages/solver/tests/chronons.test.ts | 67 +++ .../components/header/TimelineStatus.svelte | 509 +++++++++++++++--- src/lib/state/CLAUDE.md | 28 + src/lib/state/timeline.svelte.ts | 216 +++++++- src/lib/state/timeline.test.ts | 196 ++++++- src/lib/storage/storage.ts | 6 + src/lib/utils/formatters.test.ts | 54 ++ src/lib/utils/formatters.ts | 31 ++ 9 files changed, 1052 insertions(+), 89 deletions(-) create mode 100644 src/lib/utils/formatters.test.ts diff --git a/packages/solver/src/data/chronons.ts b/packages/solver/src/data/chronons.ts index 21e8b8e..96170f7 100644 --- a/packages/solver/src/data/chronons.ts +++ b/packages/solver/src/data/chronons.ts @@ -74,6 +74,26 @@ export function energyForAward(award: number, multiplier: number): number { return ENERGY_SCALE * (award / (AWARD_BASE * multiplier)) ** (1 / EXPONENT); } +/** + * Seconds until a timeline at `energy`, growing at `energyPerSecond`, pays + * `target` on a jump (first-entry bonus excluded): 0 when it already does, + * null when it never will because nothing is being produced. + * + * Real seconds. The game counts offline time in real time, but its ticks run + * a little slow while it is open, so a target hours away arrives somewhat + * later than this for a player who keeps the game open throughout. + */ +export function secondsUntilAward( + energy: number, + energyPerSecond: number, + multiplier: number, + target: number, +): number | null { + if (chrononAward(energy, multiplier) >= target) return 0; + if (!(energyPerSecond > 0)) return null; + return (energyForAward(target, multiplier) - energy) / energyPerSecond; +} + const THRESHOLD_BASE = 88; const THRESHOLD_GROWTH = 1.15; const THRESHOLD_CAP = 5000; @@ -121,6 +141,17 @@ export interface TimelineProjection { award: number; /** Seconds until the award goes up by one; null when energy is not growing. */ secondsToNext: number | null; + /** + * How long the Chronon now under way takes from start to finish, at this + * rate; null when energy is not growing. Each one takes a little longer + * than the last. + */ + chrononSeconds: number | null; + /** + * How far the energy is from this award's threshold to the next one's, 0 to + * 1 — the game's own "until next Chronon" bar. + */ + towardNext: number; /** The award a jump needs, and whether this one clears it. */ threshold: number; canJump: boolean; @@ -153,6 +184,7 @@ export function projectTimeline( const energy = timeline.energy + rate * sinceExport; const award = chrononAward(energy, multiplier); const next = Math.max(energyForAward(award + 1, multiplier), energy); + const from = Math.min(energyForAward(award, multiplier), energy); const threshold = jumpThreshold(timeline.generation); return { sinceExport, @@ -160,6 +192,8 @@ export function projectTimeline( elapsedSeconds: timeline.elapsedSeconds + sinceExport, award, secondsToNext: rate > 0 ? (next - energy) / rate : null, + chrononSeconds: rate > 0 ? (next - from) / rate : null, + towardNext: next > from ? (energy - from) / (next - from) : 0, threshold, canJump: award >= threshold, }; diff --git a/packages/solver/tests/chronons.test.ts b/packages/solver/tests/chronons.test.ts index 40d69bb..8b69205 100644 --- a/packages/solver/tests/chronons.test.ts +++ b/packages/solver/tests/chronons.test.ts @@ -15,6 +15,7 @@ import { firstEntryBonus, jumpThreshold, projectTimeline, + secondsUntilAward, } from "../src/data/chronons"; import { decodeGameExport } from "../src/encoding/gameExport"; @@ -65,6 +66,34 @@ describe("energyForAward", () => { }); }); +describe("secondsUntilAward", () => { + // The live save: E 1.77717e31 at Chronon Reactor 3, 5.1247e25 a second. + const energy = 1.77717e31; + const rate = 1.5374e26 / 3; + + it("is the time the energy takes to reach the target's threshold", () => { + const s = secondsUntilAward(energy, rate, 1.15, 11220)!; + expect(s).toBeCloseTo((energyForAward(11220, 1.15) - energy) / rate, 6); + expect(chrononAward(energy + rate * (s + 1e-3), 1.15)).toBe(11220); + expect(chrononAward(energy + rate * (s - 1), 1.15)).toBe(11219); + }); + + it("counts 11220 about five hours out, the way the game did", () => { + const s = secondsUntilAward(energy, rate, 1.15, 11220)!; + expect(s).toBeGreaterThan(5 * 3600); + expect(s).toBeLessThan(5.5 * 3600); + }); + + it("is zero for a target the award already meets", () => { + expect(secondsUntilAward(energy, rate, 1.15, 11140)).toBe(0); + expect(secondsUntilAward(energy, rate, 1.15, 50)).toBe(0); + }); + + it("never arrives with nothing produced", () => { + expect(secondsUntilAward(energy, 0, 1.15, 12000)).toBeNull(); + }); +}); + describe("jumpThreshold", () => { it("grows by 15% a jump and caps at 5000", () => { expect([0, 1, 2, 3, 4, 6].map(jumpThreshold)).toEqual([ @@ -131,6 +160,43 @@ describe("projectTimeline", () => { expect(p.secondsToNext! + 1).toBeLessThan(243); }); + it("fills the bar toward the next Chronon from nothing to whole", () => { + const at = (award: number) => + timeline.exportedAt + + (energyForAward(award, 1.15) - timeline.energy) / perSecond; + const start = at(11221); + const end = at(11222); + const bar = (t: number) => + projectTimeline(timeline, perSecond, 1.15, t).towardNext; + expect(bar(start + 0.01)).toBeLessThan(0.01); + expect(bar((start + end) / 2)).toBeCloseTo(0.5, 2); + expect(bar(end - 0.01)).toBeGreaterThan(0.99); + }); + + it("times the whole Chronon under way, and each takes longer than the last", () => { + const p = projectTimeline(timeline, perSecond, 1.15, timeline.exportedAt); + const whole = + (energyForAward(11141, 1.15) - energyForAward(11140, 1.15)) / perSecond; + expect(p.chrononSeconds!).toBeCloseTo(whole, 6); + // 11,140 -> 11,141 at export takes about 230 s; five hours on, the + // Chronons the player timed at 11,223 took about 242. + expect(p.chrononSeconds!).toBeGreaterThan(225); + expect(p.chrononSeconds!).toBeLessThan(235); + const later = projectTimeline( + timeline, + perSecond, + 1.15, + timeline.exportedAt + + (energyForAward(11223, 1.15) - timeline.energy) / perSecond + + 1, + ); + expect(later.chrononSeconds!).toBeGreaterThan(p.chrononSeconds!); + expect(later.chrononSeconds!).toBeGreaterThan(239); + expect(later.chrononSeconds!).toBeLessThan(243); + // What is left of one is never more than the whole. + expect(p.secondsToNext!).toBeLessThanOrEqual(p.chrononSeconds!); + }); + it("never runs backwards on a clock behind the export", () => { const p = projectTimeline(timeline, perSecond, 1.15, 0); expect(p.sinceExport).toBe(0); @@ -140,6 +206,7 @@ describe("projectTimeline", () => { it("has no next Chronon on a board making nothing", () => { const p = projectTimeline(timeline, 0, 1.15, timeline.exportedAt + 999); expect(p.secondsToNext).toBeNull(); + expect(p.chrononSeconds).toBeNull(); expect(p.elapsedSeconds).toBe(timeline.elapsedSeconds + 999); }); diff --git a/src/lib/components/header/TimelineStatus.svelte b/src/lib/components/header/TimelineStatus.svelte index b1ac3d7..3f42d22 100644 --- a/src/lib/components/header/TimelineStatus.svelte +++ b/src/lib/components/header/TimelineStatus.svelte @@ -1,7 +1,17 @@ + +{#snippet energy()} + +{/snippet} + +{#snippet chronon()} + +{/snippet} + {#if visible} + {/each} +
+ + {#if eta.seconds === null || eta.at === null} +

Never — nothing is producing

+ {:else if eta.seconds > OUT_OF_REACH_S} +

More than a year away at this power

+ {:else if eta.seconds > 0} +

+ In {formatSpan(eta.seconds)} + · {formatClockTime(eta.at, timelineState.now)} +

+ {#if eta.secondsWithSolves !== null} +

+ {formatSpan(eta.secondsWithSolves)} if the game ran your solves +

+ {/if} {/if} -
Next Chronon
-
- {projection.secondsToNext === null - ? "—" - : `in ${formatSpan(projection.secondsToNext)}`} -
-
Jump needs
-
- {count(projection.threshold)} · {projection.canJump - ? "ready" - : "not yet"} -
-
Chronons held
-
{count(record.timeline.chronons)}
-
Timeline
-
{formatSpan(projection.elapsedSeconds)}
- - -

- From your game export {formatTimeAgo( - record.timeline.exportedAt * 1000, - timelineState.now, - )}, game {record.gameVersion}. Counted forward at the power your game's - boards made then; re-import after changing them in the game. -

- {#if record.timeline.stampSource === "device"} - -

- The game hadn't synced its clock when it exported, so the countdown - may be off by as much as your phone's clock is. -

+

+ You'd hold {count(eta.held)}{bonusNames + ? `, or ${count(eta.held + 88)} with the +88` + : ""} +

+ {/if} + +
+ + Exported {formatTimeAgo( + record.timeline.exportedAt * 1000, + timelineState.now, + )}{record.timeline.stampSource === "device" + ? ", game clock not synced" + : ""} + + +
{:else} -

+

+
Power, all islands
+
{@render energy()}{formatNumber(power)}
+
+

{record ? "Your last import is from before game 1.1.11, which has no timeline." : "Import your game's code to count your Chronons here."}

- {/if} @@ -251,9 +442,9 @@ margin: 0; display: none; flex-direction: column; - gap: 0.6rem; + gap: 0.7rem; width: min(18rem, calc(100vw - 16px)); - padding: 0.7rem 0.8rem; + padding: 0.8rem 0.85rem; background: var(--surface-panel-solid); border: 1px solid var(--border-accent); border-radius: var(--radius); @@ -265,8 +456,7 @@ display: flex; } - h2 { - margin: 0 0 0.3rem; + .label { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 1px; @@ -274,14 +464,82 @@ color: var(--text-muted); } + .aside { + margin: 0; + font-size: var(--fs-xs); + font-weight: 500; + color: var(--text-dim); + font-variant-numeric: tabular-nums; + } + + /* A jump the game will not allow yet, or an unsynced clock: limits, `--warn`'s. */ + .limit { + font-size: var(--fs-xs); + color: var(--warn); + } + + /* Advice, not a limit and not a selection: plain text, a step up from aside. */ + .verdict { + font-size: var(--fs-xs); + color: var(--text-muted); + } + + .hero { + display: flex; + flex-direction: column; + gap: 0.25rem; + } + + .award { + display: flex; + align-items: center; + gap: 0.4rem; + font-size: var(--fs-xl); + font-weight: 700; + font-variant-numeric: tabular-nums; + line-height: 1.1; + } + + /* + * Neutral on purpose: the colour law keeps `--accent` for "selected" and the + * board's colours for buildings, and a progress bar is neither. + */ + .bar { + height: 4px; + margin-top: 0.35rem; + border-radius: var(--radius-pill); + background: var(--border); + overflow: hidden; + } + + .bar > span { + display: block; + height: 100%; + border-radius: inherit; + background: var(--text-muted); + } + + /* Each block after the headline is set off by a rule, not a heading. */ + dl, + .goal, + footer { + padding-top: 0.65rem; + border-top: 1px solid var(--border); + } + dl { display: grid; grid-template-columns: auto 1fr; - gap: 0.25rem 0.75rem; + gap: 0.3rem 0.75rem; margin: 0; font-size: var(--fs-sm); } + dl.plain { + padding-top: 0; + border-top: 0; + } + dt { color: var(--text-muted); } @@ -290,36 +548,104 @@ display: flex; align-items: center; justify-content: flex-end; - gap: 0.3rem; + gap: 0.4rem; margin: 0; + font-weight: 600; + font-variant-numeric: tabular-nums; + } + + .goal { + display: flex; + flex-direction: column; + gap: 0.45rem; + } + + .target { + display: flex; + align-items: center; + gap: 0.6rem; + } + + /* + * 16px, off the type ladder on purpose and for the same reason as the Import + * textarea: iOS Safari zooms the page in on a focused field smaller than + * that, and on a phone this field is the one being typed in. + */ + .target input { + flex: 1; + min-width: 0; + height: var(--ctl-sm); + padding: 0 0.5rem; + border: 1px solid var(--border); + border-radius: var(--radius-sm); + background: var(--surface-sunken); + color: var(--text); + font: inherit; + font-size: 16px; + font-weight: 600; + font-variant-numeric: tabular-nums; text-align: right; + } + + .target input:focus-visible { + outline: 1px solid var(--accent); + outline-offset: 1px; + } + + .chips { + display: flex; + gap: 0.35rem; + } + + .chip { + flex: 1; + height: var(--ctl-sm); + border: 1px solid var(--border); + border-radius: var(--radius-pill); + background: transparent; + color: var(--text-muted); + font-size: var(--fs-sm); font-weight: 600; font-variant-numeric: tabular-nums; + cursor: pointer; + transition: all var(--dur-fast); } - dd.strong { - font-size: var(--fs-md); + .chip:hover { + background: var(--surface-raised); + color: var(--text); } - /* A jump the game will not allow yet is a limit, which is `--warn`'s. */ - dd.short { - color: var(--warn); + /* The target in force: a selection, which is what `--accent` means. */ + .chip.active { + border-color: var(--accent); + background: var(--accent-bg); + color: var(--accent); } - .note { + .when { margin: 0; - font-size: var(--fs-xs); - color: var(--text-dim); - line-height: 1.4; + font-size: var(--fs-sm); + color: var(--text-muted); } - .note.warn { - color: var(--warn); + .when strong { + font-size: var(--fs-md); + color: var(--text); + } + + footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + font-size: var(--fs-xs); + color: var(--text-dim); } .link { - align-self: flex-start; - padding: 0.35rem 0.6rem; + flex-shrink: 0; + padding: 0.3rem 0.65rem; border-radius: var(--radius-sm); border: 1px solid var(--border); background: transparent; @@ -333,4 +659,15 @@ background: var(--surface-raised); border-color: var(--accent-dim); } + + .link.start { + align-self: flex-start; + } + + @media (pointer: coarse) { + .chip, + .link { + min-height: var(--tap); + } + } diff --git a/src/lib/state/CLAUDE.md b/src/lib/state/CLAUDE.md index 563fdc8..dcc671c 100644 --- a/src/lib/state/CLAUDE.md +++ b/src/lib/state/CLAUDE.md @@ -319,6 +319,34 @@ read. `uiState.applyGameImport` writes it through `recordImport`, after the import has landed. A record from a format version this build cannot read is dropped; the next import rewrites it. +**`chrononTarget` is a jump award the player is waiting for**, and `targetEta` +counts down to it: real seconds through the package's `secondsUntilAward`, the +moment on this device's clock, the timeline's length then, and what the player +would hold after jumping. Unset, it reads today's award, so an empty field +answers what a jump now would leave the player holding. It is kept in +`UiPrefs.chrononTarget` so it survives a reload, and **`recordImport` clears it**: +a new code is a new situation, and a goal set against the last one, left +standing, read as an import that had not taken. The game's slow ticks (see `docs/game-export.md`) are neither modelled +nor mentioned: they are the game's bug to fix. + +**`pace` reads the rate now against the timeline's average**, in Chronons an +hour: one Chronon per `chrononSeconds` against the award over the elapsed time. +Every Chronon takes longer than the last, so once the first falls below the +second, a fresh timeline that runs like this one would be earning faster — the +classic point to jump. The panel says that as a reading of two rates, not an +order: its one assumption is that the next timeline is much like this one, and +research bought at the jump only makes the next one faster. + +**`withSolvesPower` is every island with its stored solve built.** Each solve is +read off `solverStorage` and re-scored through `boardPower` on its island's +terrain under today's roster, research and anomaly, so one found before an +upgrade counts at the tier the player has now — no signature check, because the +shape is all that is used. An island whose solve makes less than its board keeps +the board. `targetEta.secondsWithSolves` is the wait at that power, shown only +when it beats the game's. Storage is not reactive, so `TimelineStatus`'s refresh +effect also reads `solverState.optimizationResult` and `appliedVariant`: a solve +landing or a variant applied is what changes a stored solve. + `now` ticks once a second only while something shows a timeline: `startClock()` returns its own stop, for a component's `$effect` to hand back. diff --git a/src/lib/state/timeline.svelte.ts b/src/lib/state/timeline.svelte.ts index 419bb5f..386c6ad 100644 --- a/src/lib/state/timeline.svelte.ts +++ b/src/lib/state/timeline.svelte.ts @@ -1,5 +1,6 @@ import { ANOMALIES, + blueprintKey, BUILDINGS, CHRONON_REACTOR_ID, chrononMultiplier, @@ -10,16 +11,23 @@ import { ISLAND_TEMPLATES, prestigeScales, projectTimeline, + secondsUntilAward, TICK_SECONDS, type AnomalyDefinition, type GameExport, type PrestigeScales, type ResolvedGameImport, + type Tile, type TimelineProjection, } from "@reactor2/solver"; import { createPlacement } from "../data/placements"; import { boardPower } from "../simulation/simulator"; -import { gameImportStorage, type SavedGameImport } from "../storage/storage"; +import { + gameImportStorage, + solverStorage, + uiStorage, + type SavedGameImport, +} from "../storage/storage"; import { configState } from "./config.svelte"; import { layoutState } from "./layout.svelte"; @@ -52,9 +60,28 @@ class TimelineState { /** Wall clock, epoch ms; `startClock` ticks it while the readout is up. */ now = $state(Date.now()); + /** + * The jump award the player is waiting for, or null for none set — in which + * case `targetEta` reads today's award: what a jump now would leave the + * player holding. Kept across reloads, and cleared by an import: a new code + * is a new situation, and a goal set against the last one left standing + * reads as an import that did not take. + */ + chrononTarget = $state( + uiStorage.loadPrefs().chrononTarget ?? null, + ); + /** Each island's power from its saved board, keyed by template id. */ #savedPower = $state>({}); + /** + * What each island's stored solve would make if it were built, keyed by + * template id; islands without one are absent. Re-scored under today's + * roster, research and anomaly on the island's own terrain, so a solve found + * before an upgrade counts at the tier the player has now. + */ + #solvePower = $state>({}); + /** Power by board and rules, so an unchanged island is not re-scored. */ #memo = new Map(); #refreshSeq = 0; @@ -91,7 +118,8 @@ class TimelineState { * call supersedes one still in flight. * * Reads all of its inputs before the first await, so an `$effect` calling it - * tracks exactly the state the answer depends on. + * tracks exactly the state the answer depends on. Stored solves are read off + * storage, which nothing tracks: the caller re-runs this when a solve lands. */ async refreshIslands(): Promise { const seq = ++this.#refreshSeq; @@ -120,8 +148,71 @@ class TimelineState { } // A memo keyed on whole boards grows with every edit; past a few rounds // of islands it is cheaper to start again than to track which are live. + // Each stored solve, scored on its island's terrain. The board on screen + // gives its terrain live — tile types only, so a paint that places a + // building does not re-score a solve that ignores hand placements. + const solves = GAME_ISLANDS.flatMap((t) => { + const saved = solverStorage.loadSolve(t.id); + if (!saved) return []; + const grid = t.id === liveId ? $state.snapshot(layoutState.grid) : null; + const code = layoutState.savedGrids[t.id]?.code ?? t.code; + return [{ id: t.id, saved, grid, code }]; + }); + const solved: Record = {}; + for (const { id, saved, grid, code } of solves) { + const terrain = grid ? blueprintKey(grid) : code; + const key = [ + "solve", + anomaly.id, + rules, + terrain, + saved.finishedAt, + saved.selectedVariant ?? 0, + ].join("|"); + let power = this.#memo.get(key); + if (power === undefined) { + const board = grid ?? (await decodeTerrain(code)); + if (seq !== this.#refreshSeq) return; + power = board + ? boardPower( + board, + BUILDINGS, + saved.result.placements.map((p) => + createPlacement(p.buildingId, p.x, p.y, upgrades), + ), + prestige, + anomaly, + ) + : 0; + this.#memo.set(key, power); + } + solved[id] = power; + } + if (this.#memo.size > GAME_ISLANDS.length * 8) this.#memo.clear(); this.#savedPower = next; + this.#solvePower = solved; + } + + /** + * Every game island's power with each stored solve built in place of the + * board here — or null when no island has a solve. An island whose solve + * makes less than the board it would replace keeps the board: nobody + * rebuilds to lose power. + */ + get withSolvesPower(): number | null { + const solved = this.#solvePower; + if (Object.keys(solved).length === 0) return null; + const live = this.#livePower; + let sum = 0; + for (const t of GAME_ISLANDS) { + const here = + live !== null && t.id === layoutState.activeTemplateId + ? live + : (this.#savedPower[t.id] ?? 0); + sum += Math.max(here, solved[t.id] ?? 0); + } + return sum; } /** The Chronon Reactor multiplier the game reported, ×1 without a record. */ @@ -144,6 +235,117 @@ class TimelineState { ); } + setChrononTarget(target: number | null) { + const valid = target !== null && Number.isFinite(target) && target > 0; + this.chrononTarget = valid ? Math.floor(target) : null; + uiStorage.savePrefs({ chrononTarget: this.chrononTarget ?? undefined }); + } + + /** + * Three round targets above today's award, sized to it: one, five and ten + * units past it, the unit a tenth of the award's order of magnitude — 11,483 + * gives 12,000, 15,000 and 20,000, and 723 gives 730, 750 and 800. + * + * Sized to the award because the exponent makes size everything: a fixed + * 10,000 is two days away for a late player and, for one at 723, a span + * longer than any date can name. + */ + get quickTargets(): number[] { + const award = this.projection?.award ?? 0; + const unit = Math.max( + 1, + 10 ** (Math.floor(Math.log10(Math.max(award, 1))) - 1), + ); + const out: number[] = []; + for (const multiple of [1, 5, 10]) { + const step = unit * multiple; + let v = (Math.floor(award / step) + 1) * step; + while (out.length && v <= out[out.length - 1]) v += step; + out.push(v); + } + return out; + } + + /** + * What an unset target reads: today's award, so an empty field answers + * "what would I hold if I jumped now?". + */ + get defaultTarget(): number { + return this.projection?.award ?? 0; + } + + /** + * When the jump award reaches the target, or null with no timeline to count. + * + * `seconds` is real time from `now`, and null when nothing is produced so the + * target never arrives; `at` is that moment on this device's clock, and + * `elapsedAt` the timeline's length then, the figure the game shows. `held` + * is what the player would hold after jumping at that point, first-entry + * bonus excluded. + */ + get targetEta(): { + target: number; + seconds: number | null; + at: number | null; + elapsedAt: number | null; + held: number; + /** + * The same wait were the game running every stored solve from now on — + * null with no solve that beats the game's power, or no wait to shorten. + */ + secondsWithSolves: number | null; + } | null { + const r = this.record; + const p = this.projection; + if (!r?.timeline || !p) return null; + const target = this.chrononTarget ?? this.defaultTarget; + const seconds = secondsUntilAward( + p.energy, + r.energyPerTick / TICK_SECONDS, + this.#multiplier, + target, + ); + const solves = this.withSolvesPower; + const secondsWithSolves = + seconds && solves !== null && solves > r.energyPerTick + ? secondsUntilAward( + p.energy, + solves / TICK_SECONDS, + this.#multiplier, + target, + ) + : null; + return { + target, + seconds, + at: seconds === null ? null : this.now + seconds * 1000, + elapsedAt: seconds === null ? null : p.elapsedSeconds + seconds, + // A target already met is met by today's award, which a jump pays. + held: r.timeline.chronons + Math.max(target, p.award), + secondsWithSolves, + }; + } + + /** + * How fast the timeline earns now against how fast it has earned on + * average, in Chronons an hour — null with no timeline, or nothing produced. + * + * The award grows with energy to the power 0.135, so every Chronon takes + * longer than the last. If the next timeline runs much like this one, the + * moment the rate now falls below this timeline's average is the moment a + * fresh timeline starts earning faster than staying does — the classic + * point to jump. That "if" is the whole caveat, and Time Lab research bought + * at the jump only makes the next one faster, so this errs late, not early. + */ + get pace(): { nowPerHour: number; averagePerHour: number } | null { + const p = this.projection; + if (!p || p.chrononSeconds === null || p.elapsedSeconds <= 0) return null; + return { + nowPerHour: 3600 / p.chrononSeconds, + averagePerHour: p.award / (p.elapsedSeconds / 3600), + }; + } + /** * The anomalies a jump would still pay the first-entry bonus for — the * choices a player makes at the jump, so the readout lists them by name. @@ -225,6 +427,16 @@ class TimelineState { this.record = record; this.now = Date.now(); gameImportStorage.save(record); + this.setChrononTarget(null); + } +} + +/** A saved board's terrain, or null if it cannot be read. */ +async function decodeTerrain(code: string): Promise { + try { + return (await decodeBlueprint(code)).grid; + } catch { + return null; } } diff --git a/src/lib/state/timeline.test.ts b/src/lib/state/timeline.test.ts index 53864e0..ea9a7c5 100644 --- a/src/lib/state/timeline.test.ts +++ b/src/lib/state/timeline.test.ts @@ -29,7 +29,49 @@ const { decodeGameExport, resolveGameExport, applyInProgress, TICK_SECONDS } = const { configState } = await import("./config.svelte"); const { layoutState } = await import("./layout.svelte"); const { timelineState } = await import("./timeline.svelte"); -const { gameImportStorage } = await import("../storage/storage"); +const { gameImportStorage, solverStorage, uiStorage } = + await import("../storage/storage"); + +/** + * Stages a stored solve for `templateId` built from `placements`. Only the + * shape is read back — the timeline re-scores it — so the figures are left + * at zero. + */ +function stageSolve( + templateId: string, + placements: { buildingId: string; x: number; y: number }[], +) { + solverStorage.saveSolve({ + templateId, + signature: "", + result: { + totalPower: 0, + placements: placements.map(({ buildingId, x, y }) => ({ + buildingId, + x, + y, + baseValue: 0, + powerGenerated: 0, + heatProduced: 0, + heatConsumed: 0, + wasteHeatGenerated: 0, + coolingProvided: 0, + coolingReceived: 0, + })), + activeTilesCount: 0, + unusedTilesCount: 0, + summary: { + totalHeatProduced: 0, + totalHeatConsumed: 0, + totalWasteGenerated: 0, + totalCoolingCapacity: 0, + }, + theoreticalMaxPower: 0, + }, + durationMs: 1, + finishedAt: Date.now(), + }); +} const FIXTURES = join( dirname(fileURLToPath(import.meta.url)), @@ -156,6 +198,158 @@ describe("the timeline", () => { ]); }); + it("reads today's award until a target is set", async () => { + const { exp } = await importFixture("gen1_cryo_city41"); + timelineState.setChrononTarget(null); + timelineState.now = exp.timeline!.exportedAt * 1000; + // An empty field answers "what would a jump now leave me holding?". + expect(timelineState.targetEta).toMatchObject({ + target: exp.timeline!.jumpAward, + seconds: 0, + held: exp.timeline!.chronons + exp.timeline!.jumpAward, + }); + }); + + it("sizes the quick targets to the award", async () => { + let { exp } = await importFixture("gen2_city52_9c43e4b7"); + timelineState.now = exp.timeline!.exportedAt * 1000; + expect(timelineState.quickTargets).toEqual([12000, 15000, 20000]); + + ({ exp } = await importFixture("gen2_cryo_city34")); + timelineState.now = exp.timeline!.exportedAt * 1000; + expect(timelineState.quickTargets).toEqual([730, 750, 800]); + }); + + /* + * The case that printed "Invalid Date": at 723 a fixed 10,000 was some + * billion days out. The nearest chip now has to be a wait a player can plan. + */ + it("offers a small award a chip it can reach this year", async () => { + const { exp } = await importFixture("gen2_cryo_city34"); + timelineState.now = exp.timeline!.exportedAt * 1000; + timelineState.setChrononTarget(timelineState.quickTargets[0]); + const eta = timelineState.targetEta!; + expect(eta.target).toBe(730); + expect(eta.seconds!).toBeGreaterThan(0); + expect(eta.seconds!).toBeLessThan(365 * 86400); + }); + + it("counts down to a set target, and remembers it", async () => { + const { exp } = await importFixture("gen2_city52_9c43e4b7"); + const t = exp.timeline!; + timelineState.now = t.exportedAt * 1000; + timelineState.setChrononTarget(t.jumpAward + 10); + + const eta = timelineState.targetEta!; + expect(eta.target).toBe(t.jumpAward + 10); + // Ten Chronons on from 11,241, at about four minutes each. + expect(eta.seconds!).toBeGreaterThan(9 * 230); + expect(eta.seconds!).toBeLessThan(10 * 250); + expect(eta.at).toBe(timelineState.now + eta.seconds! * 1000); + expect(eta.elapsedAt).toBe(t.elapsedSeconds + eta.seconds!); + + // Half-way there, half the wait is left. + timelineState.now += (eta.seconds! / 2) * 1000; + expect(timelineState.targetEta!.seconds!).toBeCloseTo(eta.seconds! / 2, 3); + + expect(uiStorage.loadPrefs().chrononTarget).toBe(t.jumpAward + 10); + }); + + it("reads a target already met as reached, paying today's award", async () => { + const { exp } = await importFixture("gen2_city52_9c43e4b7"); + const t = exp.timeline!; + timelineState.now = t.exportedAt * 1000; + timelineState.setChrononTarget(500); + expect(timelineState.targetEta).toMatchObject({ + seconds: 0, + held: t.chronons + t.jumpAward, + }); + }); + + it("starts a new import from today's award, not the last target", async () => { + await importFixture("gen2_city52_9c43e4b7"); + timelineState.setChrononTarget(15000); + const { exp } = await importFixture("gen1_cryo_city41"); + timelineState.now = exp.timeline!.exportedAt * 1000; + expect(timelineState.chrononTarget).toBeNull(); + expect(uiStorage.loadPrefs().chrononTarget).toBeUndefined(); + expect(timelineState.targetEta).toMatchObject({ + target: exp.timeline!.jumpAward, + seconds: 0, + }); + }); + + it("clears a target that is not a positive number", () => { + timelineState.setChrononTarget(-4); + expect(timelineState.chrononTarget).toBeNull(); + expect(uiStorage.loadPrefs().chrononTarget).toBeUndefined(); + }); + + it("reads the pace now against the timeline's average", async () => { + const { exp } = await importFixture("gen2_city52_9c43e4b7"); + const t = exp.timeline!; + timelineState.now = t.exportedAt * 1000; + const pace = timelineState.pace!; + const p = timelineState.projection!; + expect(pace.nowPerHour).toBeCloseTo(3600 / p.chrononSeconds!, 9); + expect(pace.averagePerHour).toBeCloseTo( + t.jumpAward / (t.elapsedSeconds / 3600), + 9, + ); + // Thirteen days in, one Chronon takes minutes against an average of + // seconds-apart: this save is past the point a fresh timeline beats. + expect(pace.nowPerHour).toBeLessThan(pace.averagePerHour); + }); + + it("has no solve figures until an island has a stored solve", async () => { + await importFixture("gen2_city52_9c43e4b7"); + await timelineState.refreshIslands(); + expect(timelineState.withSolvesPower).toBeNull(); + expect(timelineState.targetEta!.secondsWithSolves).toBeNull(); + }); + + it("builds each solve in place of a weaker board, and never a stronger one", async () => { + const { resolved } = await importFixture("gen2_city52_9c43e4b7"); + await timelineState.refreshIslands(); + const total = timelineState.totalPower; + const island2 = resolved.islands.find((i) => i.templateId === "island2")!; + + // A solve that is the island's own board adds nothing. + stageSolve("island2", island2.placements); + await timelineState.refreshIslands(); + expect(timelineState.withSolvesPower).toBeCloseTo(total, -20); + + // An empty "solve" makes less than the board, so the board stays. + stageSolve("island2", []); + await timelineState.refreshIslands(); + expect(timelineState.withSolvesPower).toBeCloseTo(total, -20); + }); + + it("counts a target down faster with solves that beat the game's power", async () => { + const { exp, resolved } = await importFixture("gen2_city52_9c43e4b7"); + const island2 = resolved.islands.find((i) => i.templateId === "island2")!; + stageSolve("island2", island2.placements); + await timelineState.refreshIslands(); + // Stand the game's boards at half their power: the solves now beat them. + timelineState.record = { + ...timelineState.record!, + energyPerTick: timelineState.record!.energyPerTick / 2, + }; + timelineState.now = exp.timeline!.exportedAt * 1000; + timelineState.setChrononTarget(exp.timeline!.jumpAward + 50); + + const eta = timelineState.targetEta!; + expect(eta.secondsWithSolves!).toBeGreaterThan(0); + // Twice the power, half the wait. + expect(eta.secondsWithSolves!).toBeCloseTo(eta.seconds! / 2, 0); + }); + + it("offers no bonus once every anomaly has been entered", async () => { + // Cryo, Singularity and Tidal all entered, under a legacy Tidal header. + await importFixture("gen6_tidal_city49"); + expect(timelineState.unenteredAnomalies).toEqual([]); + }); + it("has no projection for a code from before the timeline section", async () => { await importFixture("city34-timeline3"); expect(timelineState.record!.timeline).toBeNull(); diff --git a/src/lib/storage/storage.ts b/src/lib/storage/storage.ts index 47c1b52..f3d68ec 100755 --- a/src/lib/storage/storage.ts +++ b/src/lib/storage/storage.ts @@ -100,6 +100,12 @@ export interface UiPrefs { analyticsDisabled?: boolean; /** How far `saveLayoutImage` scales the exported PNG up. */ imageScale: ImageScale; + /** + * The jump award the timeline panel counts down to — see + * `timelineState.chrononTarget`. Optional: absent means the player has not + * set one, and the panel reads today's award instead. + */ + chrononTarget?: number; } const DEFAULT_UI_PREFS: UiPrefs = { diff --git a/src/lib/utils/formatters.test.ts b/src/lib/utils/formatters.test.ts new file mode 100644 index 0000000..9e7d2d8 --- /dev/null +++ b/src/lib/utils/formatters.test.ts @@ -0,0 +1,54 @@ +/** + * The two time formats the timeline panel speaks in: a span of game time, and + * a moment ahead on the device's clock. + */ +import { describe, expect, it } from "vitest"; +import { formatClockTime, formatSpan } from "./formatters"; + +describe("formatSpan", () => { + it("reads to its two largest units", () => { + expect(formatSpan(37)).toBe("37s"); + expect(formatSpan(242)).toBe("4m 02s"); + expect(formatSpan(4 * 3600 + 17 * 60 + 5)).toBe("4h 17m"); + expect(formatSpan(13 * 86400 + 4 * 3600 + 59)).toBe("13d 4h"); + }); + + it("never goes below zero or into fractions", () => { + expect(formatSpan(-5)).toBe("0s"); + expect(formatSpan(59.9)).toBe("59s"); + }); +}); + +describe("formatClockTime", () => { + // Local noon, so neither an hour ahead nor behind crosses a day boundary. + const now = new Date(2026, 9, 22, 12, 0).getTime(); + const hours = (h: number) => now + h * 3600 * 1000; + + it("names today and tomorrow", () => { + expect(formatClockTime(hours(3), now)).toMatch(/^today /); + expect(formatClockTime(hours(20), now)).toMatch(/^tomorrow /); + }); + + it("names the weekday within the week, and the date past it", () => { + const inThree = hours(24 * 3); + const weekday = new Date(inThree).toLocaleDateString(undefined, { + weekday: "short", + }); + expect(formatClockTime(inThree, now).startsWith(`${weekday} `)).toBe(true); + + const inNine = hours(24 * 9); + const date = new Date(inNine).toLocaleDateString(undefined, { + month: "short", + day: "numeric", + }); + expect(formatClockTime(inNine, now).startsWith(`${date} `)).toBe(true); + }); + + it("names no moment past the range a date can hold", () => { + expect(formatClockTime(now + 1e9 * 86400 * 1000, now)).toBe("—"); + }); + + it("reads a moment already past as today", () => { + expect(formatClockTime(hours(-1), now)).toMatch(/^today /); + }); +}); diff --git a/src/lib/utils/formatters.ts b/src/lib/utils/formatters.ts index e33f1ee..23ac3f3 100755 --- a/src/lib/utils/formatters.ts +++ b/src/lib/utils/formatters.ts @@ -62,6 +62,37 @@ export function formatSpan(seconds: number): string { return `${sec}s`; } +/** + * A moment ahead, as a player would say it: "today 23:45", "tomorrow 06:10", + * "Fri 14:00" within the week, then "Oct 30 14:00". In the device's own locale + * and time zone, so the clock reads the way the phone beside it does. + */ +export function formatClockTime( + epochMs: number, + now: number = Date.now(), +): string { + const at = new Date(epochMs); + // Past the range a Date can hold it is "Invalid Date", not a moment. + if (Number.isNaN(at.getTime())) return "—"; + const time = at.toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + }); + const midnight = (d: Date) => + new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); + const days = Math.round((midnight(at) - midnight(new Date(now))) / 86400000); + if (days <= 0) return `today ${time}`; + if (days === 1) return `tomorrow ${time}`; + if (days < 7) { + return `${at.toLocaleDateString(undefined, { weekday: "short" })} ${time}`; + } + const date = at.toLocaleDateString(undefined, { + month: "short", + day: "numeric", + }); + return `${date} ${time}`; +} + // --------------------------------------------------------------------------- // Tile coordinates // --------------------------------------------------------------------------- From 78f028917d9a5bed52892a848308eade0bfdf844 Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:57:18 +0300 Subject: [PATCH 6/9] Solve every unlocked island in one press "Solve all islands" (Setup's Islands tab, and the timeline panel's new Solves row) solves each island the game has unlocked in turn at the chosen solve mode, keeps each one's best, and returns to the island the player started on. It walks the islands rather than solving them off screen: each is opened as the island list opens one and run through the same runOptimizer the Run button uses, so the defence of a held layout, the per-island merge and filing under the right island all carry over unchanged. A stored solve is defended whenever it was searched under the same anomaly and plan. Stop ends the batch after the island running, a hidden tab holds the next one back, and the readout's run chip counts "3/8". Never automatic: a solve takes every core for its budget, and Quick often loses to a hand-built board. --- .../components/header/TimelineStatus.svelte | 45 +++++ .../inspector/BoardStatsCard.svelte | 4 + .../sidebar/TemplateSelector.svelte | 59 ++++++- src/lib/state/CLAUDE.md | 21 +++ src/lib/state/solveAll.test.ts | 156 ++++++++++++++++++ src/lib/state/timeline.svelte.ts | 5 + src/lib/state/ui.svelte.ts | 117 +++++++++++++ 7 files changed, 406 insertions(+), 1 deletion(-) create mode 100644 src/lib/state/solveAll.test.ts diff --git a/src/lib/components/header/TimelineStatus.svelte b/src/lib/components/header/TimelineStatus.svelte index 3f42d22..e26382e 100644 --- a/src/lib/components/header/TimelineStatus.svelte +++ b/src/lib/components/header/TimelineStatus.svelte @@ -165,6 +165,11 @@ if (e.newState === "open") place(); } + function solveAll() { + panel?.hidePopover(); + void uiState.solveAllIslands(); + } + function importCode() { panel?.hidePopover(); uiState.openImport(); @@ -291,6 +296,29 @@ {formatNumber(withSolves)} {/if} + +
Solves
+
+ {#if uiState.solveAll} + + solving {uiState.solveAll.done + 1} of {uiState.solveAll.total} + + {:else} + + {timelineState.solvedIslands} of {uiState.solveAllTargets.length} + islands + + {#if uiState.canSolveAll} + + {/if} + {/if} +
Held
{@render chronon()}{count(record.timeline.chronons)}
Timeline
@@ -660,12 +688,29 @@ border-color: var(--accent-dim); } + .mini { + padding: 0.1rem 0.5rem; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: transparent; + color: var(--text); + font-size: var(--fs-xs); + font-weight: 600; + cursor: pointer; + } + + .mini:hover { + background: var(--surface-raised); + border-color: var(--accent-dim); + } + .link.start { align-self: flex-start; } @media (pointer: coarse) { .chip, + .mini, .link { min-height: var(--tap); } diff --git a/src/lib/components/inspector/BoardStatsCard.svelte b/src/lib/components/inspector/BoardStatsCard.svelte index 15c0b7e..b967496 100755 --- a/src/lib/components/inspector/BoardStatsCard.svelte +++ b/src/lib/components/inspector/BoardStatsCard.svelte @@ -593,6 +593,10 @@ > {#if runMode}{runMode.label}{/if} + + {#if uiState.solveAll}{uiState.solveAll.done + 1}/{uiState.solveAll.total}{/if} {solverState.isStopping ? "stopping" : countdown} diff --git a/src/lib/components/sidebar/TemplateSelector.svelte b/src/lib/components/sidebar/TemplateSelector.svelte index cf96725..99336d2 100755 --- a/src/lib/components/sidebar/TemplateSelector.svelte +++ b/src/lib/components/sidebar/TemplateSelector.svelte @@ -8,7 +8,8 @@ } from "../../state"; import { ISLAND_TEMPLATES, MAX_CUSTOM_ISLANDS } from "@reactor2/solver"; import type { IslandTemplate } from "../../types/building"; - import { Plus, RotateCcw, Trash2 } from "lucide-svelte"; + import { ListChecks, Plus, RotateCcw, Trash2 } from "lucide-svelte"; + import { formatSpan } from "../../utils"; import { onDestroy } from "svelte"; import { createConfirmArm } from "../confirmArm.svelte"; @@ -77,9 +78,33 @@ if (fallback) await selectTemplate(fallback); } } + + /* + * A rough length for "Solve all": the run the current mode would take on + * the island on screen, once per island. Islands differ in size, so this + * is a scale ("about four minutes"), not a promise. + */ + let solveAllEstimate = $derived( + formatSpan( + (solverState.estimatedRunMs * uiState.solveAllTargets.length) / 1000, + ), + );
+ + {#if uiState.canSolveAll} + + {/if} + + {#if timelineState.planBudget !== null} +
Time Lab
+
+ {count(timelineState.planBudget)} to spend + +
+ {/if}
Held
{@render chronon()}{count(record.timeline.chronons)}
Timeline
diff --git a/src/lib/components/index.ts b/src/lib/components/index.ts index 802b7ba..c7829c3 100755 --- a/src/lib/components/index.ts +++ b/src/lib/components/index.ts @@ -19,3 +19,4 @@ export { default as SettingsModal } from "./modals/SettingsModal.svelte"; export { default as SolveModal } from "./modals/SolveModal.svelte"; export { default as SolveModeInfoModal } from "./modals/SolveModeInfoModal.svelte"; export { default as UpgradePlanModal } from "./modals/UpgradePlanModal.svelte"; +export { default as TimeLabPlannerModal } from "./modals/TimeLabPlannerModal.svelte"; diff --git a/src/lib/components/modals/TimeLabPlannerModal.svelte b/src/lib/components/modals/TimeLabPlannerModal.svelte new file mode 100644 index 0000000..c088b5d --- /dev/null +++ b/src/lib/components/modals/TimeLabPlannerModal.svelte @@ -0,0 +1,425 @@ + + +{#if open && levels && budget !== null} + uiState.closeModal()}> +
+
+
To spend after the jump
+
+ + {count(budget)} +
+
Planned
+
{count(cost)}
+
Left
+
{count(budget - cost)}
+ {#if power && power.plan !== power.base} +
Plan's power
+
{pct(power.plan / power.base)}
+ {/if} +
+

+ {eta && eta.seconds + ? `Jumping at ${count(eta.target)}, the panel's target.` + : "Jumping now."} + {#if bonusNames} + + {/if} +

+
+ + {#each GROUPS as group (group.label)} +

{group.label}

+
    + {#each group.ids as id (id)} + {@const r = byId.get(id)!} + {@const now = levels[id]} + {@const extra = plan[id] ?? 0} + {@const max = r.costs.length} + {@const to = now + extra} + {@const note = to < max ? impact(r) : null} +
  • 0}> + +
    +
    + {r.name} + + Lv {now}{#if extra}{` → ${to}`}{/if}/{max} +
    +
    + {r.effect}: + {valueAt(r, now)}{#if extra}{" → "}{valueAt(r, to)}{/if} +
    + +
    +
    + {#if extra > 0} + + {/if} + {#if to < max} + + {/if} +
    +
  • + {/each} +
+ {/each} + + {#if cost > 0} + + {/if} +
+{/if} + + diff --git a/src/lib/components/sidebar/ConfigSidebar.svelte b/src/lib/components/sidebar/ConfigSidebar.svelte index 04d7c44..bfd07ee 100755 --- a/src/lib/components/sidebar/ConfigSidebar.svelte +++ b/src/lib/components/sidebar/ConfigSidebar.svelte @@ -1,5 +1,5 @@ + + + + +{#snippet cash()} + +{/snippet} + +
+
+ {#if planning || !m} +
+ + + Planning the steps{planning && planning.total + ? ` · ${Math.round((planning.done / planning.total) * 100)}%` + : "…"} + + +
+ {:else} +
+ + {index === 0 ? "Start" : `Step ${index} of ${total}`} + + + + {formatNumber(power)} + {#if before !== null && delta(power, before)} + {delta(power, before)} + {/if} + + +
+ +
+ {#if step} + {#if iconOf(step)} + + {/if} + {describe(step)} + {:else} + + Your board in Edit. {summary} to reach {formatNumber(end)}. + + {/if} +
+ + {#if index === total && m.plan.stoppedEarly} +

+ Done: this already makes the layout's power. The rest would only + rearrange buildings. +

+ {/if} + {#if price && (price.spend > 0 || price.refund > 0)} + +
+ {#if price.spend > 0} +
Costs
+
{@render cash()}{formatNumber(price.spend)}
+ {/if} + {#if price.refund > 0} +
Refunds
+
{@render cash()}{formatNumber(price.refund)}
+ {/if} +
+ {/if} + {#if index === 0 && money && (money.spend > 0 || money.refund > 0)} + +
+
Cash needed
+
{@render cash()}{formatNumber(money.spend)}
+
Refunded
+
{@render cash()}{formatNumber(money.refund)}
+ {#if money.peak > 0 && money.peak < money.spend} +
Cash on hand needed
+
{@render cash()}{formatNumber(money.peak)}
+ {/if} +
+ {/if} + {#if index === 0 && lowest < power} +

+ Lowest on the way: {formatNumber(lowest)}, {delta(lowest, power)} + from now. +

+ {/if} + + + {/if} +
+
+ + diff --git a/src/lib/components/index.ts b/src/lib/components/index.ts index c7829c3..244cf58 100755 --- a/src/lib/components/index.ts +++ b/src/lib/components/index.ts @@ -11,6 +11,7 @@ export { default as Header } from "./header/Header.svelte"; export { default as PreviewBanner } from "./header/PreviewBanner.svelte"; export { default as PixiCanvas } from "./canvas/PixiCanvas.svelte"; export { default as HudToolbar } from "./hud/HudToolbar.svelte"; +export { default as MoveStepsBar } from "./hud/MoveStepsBar.svelte"; export { default as BoardStatsCard } from "./inspector/BoardStatsCard.svelte"; export { default as ConfigSidebar } from "./sidebar/ConfigSidebar.svelte"; export { default as ShareModal } from "./modals/ShareModal.svelte"; diff --git a/src/lib/components/inspector/BoardStatsCard.svelte b/src/lib/components/inspector/BoardStatsCard.svelte index b967496..bc814e8 100755 --- a/src/lib/components/inspector/BoardStatsCard.svelte +++ b/src/lib/components/inspector/BoardStatsCard.svelte @@ -36,6 +36,7 @@ ChevronUp, Copy, Eye, + ListOrdered, Hammer, Loader2, RotateCcw, @@ -206,12 +207,17 @@ /* * The solve reports its own total rather than having it re-summed here: it * is the figure the search actually optimised, and `#scoreLayout` is what - * produced both it and the rows above. + * produced both it and the rows above. In step mode the board on screen is + * the island partway there, so the card reads that board's power instead — + * a card printing the finished solve over a half-built island is the + * mismatch `visiblePlacements` exists to prevent. */ let power = $derived( - panel === "solver" - ? (solverState.optimizationResult?.totalPower ?? 0) - : board.power, + uiState.stepsActive + ? uiState.visiblePower + : panel === "solver" + ? (solverState.optimizationResult?.totalPower ?? 0) + : board.power, ); /* @@ -602,6 +608,21 @@ > {:else if panel === "solver" && !layoutState.isPreview} + + {#if uiState.canPlanMoveSteps && !uiState.stepsActive} + + {/if} +
@@ -663,6 +668,9 @@ } .sidebar-foot { + display: flex; + flex-direction: column; + gap: 0.6rem; padding: 0.75rem 1rem; border-top: 1px solid var(--accent-faint); /* A region set apart inside the panel — see `--surface-inset`, which the diff --git a/src/lib/components/sidebar/SolveAllButton.svelte b/src/lib/components/sidebar/SolveAllButton.svelte new file mode 100644 index 0000000..17cee3f --- /dev/null +++ b/src/lib/components/sidebar/SolveAllButton.svelte @@ -0,0 +1,70 @@ + + +{#if uiState.canSolveAll} + +{/if} + + diff --git a/src/lib/components/sidebar/TemplateSelector.svelte b/src/lib/components/sidebar/TemplateSelector.svelte index 99336d2..60def17 100755 --- a/src/lib/components/sidebar/TemplateSelector.svelte +++ b/src/lib/components/sidebar/TemplateSelector.svelte @@ -5,11 +5,12 @@ layoutState, solverState, uiState, + viewportState, } from "../../state"; import { ISLAND_TEMPLATES, MAX_CUSTOM_ISLANDS } from "@reactor2/solver"; import type { IslandTemplate } from "../../types/building"; - import { ListChecks, Plus, RotateCcw, Trash2 } from "lucide-svelte"; - import { formatSpan } from "../../utils"; + import { Plus, RotateCcw, Trash2 } from "lucide-svelte"; + import SolveAllButton from "./SolveAllButton.svelte"; import { onDestroy } from "svelte"; import { createConfirmArm } from "../confirmArm.svelte"; @@ -78,31 +79,15 @@ if (fallback) await selectTemplate(fallback); } } - - /* - * A rough length for "Solve all": the run the current mode would take on - * the island on screen, once per island. Islands differ in size, so this - * is a scale ("about four minutes"), not a promise. - */ - let solveAllEstimate = $derived( - formatSpan( - (solverState.estimatedRunMs * uiState.solveAllTargets.length) / 1000, - ), - );
- {#if uiState.canSolveAll} - + {#if viewportState.isCompact} +
{/if}