From f5a1bba99233976679a4f7085d874d50c740452d Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:28:45 +0300 Subject: [PATCH 1/3] Drop idle buildings, move empty tiles to the edge, cheapest tie first Right-sizing swapped a building with no load for the cheapest tier of its role and left it standing idle, which is how a Heat Sink #1 ended up doing nothing beside a #8. A building with no load is now tried for removal first, under the same power, online and plan guard as a swap. A new last pass moves the empty tiles a layout leaves inside the land out to the shore and into corners: a building nearer the edge steps into each hole, kept only if power holds, no producer goes offline, nothing new goes idle and the plan still runs. On a player's eight Singularity solves it took 24 interior holes to none at no power, in 0-145ms per board. Among layouts that tie on power, the cheapest to build (the game's prices, each copy dearer than the last; then fewest buildings) is the one an island returns, with its alternates in the same order. --- packages/solver/CLAUDE.md | 14 +- packages/solver/src/data/buildingPrices.ts | 66 +++++++ packages/solver/src/solver/placementSearch.ts | 57 ++++-- .../solver/src/solver/search/emptyTiles.ts | 178 ++++++++++++++++++ .../solver/src/solver/search/rightSize.ts | 30 ++- packages/solver/tests/buildingPrices.test.ts | 38 +++- .../tests/placementSearch.downgrade.test.ts | 24 ++- .../tests/placementSearch.emptyTiles.test.ts | 91 +++++++++ 8 files changed, 477 insertions(+), 21 deletions(-) create mode 100644 packages/solver/src/solver/search/emptyTiles.ts create mode 100644 packages/solver/tests/placementSearch.emptyTiles.test.ts diff --git a/packages/solver/CLAUDE.md b/packages/solver/CLAUDE.md index 68d2e68..3c2f7ad 100644 --- a/packages/solver/CLAUDE.md +++ b/packages/solver/CLAUDE.md @@ -620,7 +620,7 @@ is the entry point. `planSolve()` does the shared setup: reserved before the layout exists and converges long before its cap, so what it hands back becomes another short walk rather than idle time. Each stage is a file under `search/` (`seed`, `anneal`, `composition`, `repair`, - `rightSize`, `pooledCoolers`, over the shared `placement` and `stability` + `rightSize`, `pooledCoolers`, `emptyTiles`, over the shared `placement` and `stability` primitives); `placementSearch.ts` keeps `solveIsland`, the budget split, the deterministic replay and `internals`, and stays the one module anything outside imports the search from. The reasoning for each stage is in @@ -662,7 +662,17 @@ at 2%, so nothing in the walk prefers the tier a tile actually needs, and the roster's top cooler lands where a twentieth of it would do — real money the player spends on capacity that never runs. Each swap is re-simulated and kept only if power holds and every producer stays online, so it can change which -building sits on a tile and nothing else. Tied layouts go through it too. +building sits on a tile and nothing else — except a building doing nothing at +all, which it takes away rather than shrinking: every tier covers a load of +zero, so such a cooler used to become the cheapest one and stand there idle. +Tied layouts go through it too. + +**`gatherEmptyTiles` runs last, under every rule**, and is the same kind of +pass: it moves the holes a layout leaves inside the land out to the shore and +into corners, a nearer-the-edge building stepping into each, re-simulated and +kept only if power holds, no producer goes offline, nothing new goes idle and +the plan holds. Under a pool it leaves coolers where `gatherPooledCoolers` put +them. Its budget (`EMPTY_GATHER_BUDGET_MS`) is added to a run. **`distribution.ts` is a port of Unity's `FlowNetwork.cs`.** Two shapes in it are load-bearing and look like details: diff --git a/packages/solver/src/data/buildingPrices.ts b/packages/solver/src/data/buildingPrices.ts index b0e290b..8687454 100644 --- a/packages/solver/src/data/buildingPrices.ts +++ b/packages/solver/src/data/buildingPrices.ts @@ -1,3 +1,4 @@ +import { findBuilding } from "./buildings"; import { TIME_LAB } from "./timeLab"; /** @@ -85,3 +86,68 @@ export function sellRefund( ): number { return copies > 0 ? buildPrice(base, copies, rules) * rules.refund : 0; } + +/** The price rules of a player with none of the price research. */ +const BASE_RULES: PriceRules = { + scaler: COST_SCALER[0], + discount: 1, + refund: REFUND[0], +}; + +/** + * What building `layout` from an empty board costs, every copy at the price + * the next one would be. + * + * This is what ranks layouts that tie on power, so it only has to order them + * right, and the research that lowers prices mostly cannot change the order: + * both reductions scale every price alike. The scaler can, a little, and the + * copies standing on other islands too, so this is the board's own cost under + * the base scaler — a ranking, not a quote. + */ +export function layoutCost( + layout: readonly { buildingId: string }[], + rules: PriceRules = BASE_RULES, +): number { + const copies = new Map(); + for (const p of layout) + copies.set(p.buildingId, (copies.get(p.buildingId) ?? 0) + 1); + let cost = 0; + for (const [id, n] of copies) { + const base = findBuilding(id)?.price ?? 0; + for (let k = 0; k < n; k++) cost += buildPrice(base, k, rules); + } + return cost; +} + +/** + * Relative slack for "the same cost": two layouts holding the same buildings + * sum them in a different order and can disagree in the last bits. + */ +const COST_TIE_RELATIVE_TOLERANCE = 1e-9; + +/** + * Orders layouts that tie on power cheapest first: by `layoutCost`, then — the + * prices span thirty orders of magnitude, so a cooler more or less is lost in + * the cost of a reactor — by how many buildings stand, fewest first, so the + * layout leaving more of the land empty wins. Stable, so layouts neither + * figure separates keep the order they came in. + * + * Each layout is costed once, not once per comparison. + */ +export function cheapestFirst( + items: readonly T[], + placementsOf: (item: T) => readonly { buildingId: string }[], +): T[] { + return items + .map((item) => { + const placements = placementsOf(item); + return { item, cost: layoutCost(placements), count: placements.length }; + }) + .sort((a, b) => + Math.abs(a.cost - b.cost) > + COST_TIE_RELATIVE_TOLERANCE * Math.max(a.cost, b.cost) + ? a.cost - b.cost + : a.count - b.count, + ) + .map(({ item }) => item); +} diff --git a/packages/solver/src/solver/placementSearch.ts b/packages/solver/src/solver/placementSearch.ts index 3e57fd2..b88764b 100755 --- a/packages/solver/src/solver/placementSearch.ts +++ b/packages/solver/src/solver/placementSearch.ts @@ -1,3 +1,4 @@ +import { cheapestFirst } from "../data/buildingPrices"; import { AlternateCollector, isDistinctLayout, powerTies } from "./alternates"; import { EPS } from "./constants"; import { buildIslandContext, type IslandContext } from "./context"; @@ -20,6 +21,7 @@ import { targetCanBeat, targetCompositions, } from "./search/composition"; +import { EMPTY_GATHER_BUDGET_MS, gatherEmptyTiles } from "./search/emptyTiles"; import { emptyPlacement, isDirectProducer, @@ -184,6 +186,10 @@ async function finalizeAlternates( // cuts short is still valid, only less gathered. const gatherDeadlineMs = performance.now() + EVACUATE_BUDGET_MS + GATHER_BUDGET_MS; + // And one for the holes, counted in time actually spent: the coolers' pass + // is a no-op under every rule but a pool, and its unused budget is not this + // one's to take. + let emptyLeftMs = EMPTY_GATHER_BUDGET_MS; for (const layout of collector.layouts()) { // This runs after the search's deadline, and each alternate is a few @@ -210,12 +216,21 @@ async function finalizeAlternates( ctx, gatherDeadlineMs, ); - if (!powerTies(sized.power, primaryPower)) continue; + const emptyStartedMs = performance.now(); + const tidied = gatherEmptyTiles( + sized.rows, + sized.power, + effectiveBuildings, + ctx, + emptyStartedMs + emptyLeftMs, + ); + emptyLeftMs -= performance.now() - emptyStartedMs; + if (!powerTies(tidied.power, primaryPower)) continue; - const rows = toPlacedBuildings(sized.rows); + const rows = toPlacedBuildings(tidied.rows); if (!isDistinctLayout(rows, kept)) continue; kept.push(rows); - out.push({ placements: rows, powerOutput: sized.power }); + out.push({ placements: rows, powerOutput: tidied.power }); } return out; @@ -686,19 +701,30 @@ export async function solveIsland( ctx, performance.now() + EVACUATE_BUDGET_MS + GATHER_BUDGET_MS, ); - const placements = toPlacedBuildings(sized.rows); - return { + // Then push the holes the layout leaves out to the shore and the corners. + const tidied = gatherEmptyTiles( + sized.rows, + sized.power, + effectiveBuildings, + ctx, + performance.now() + EMPTY_GATHER_BUDGET_MS, + ); + const placements = toPlacedBuildings(tidied.rows); + const alternates = await finalizeAlternates( + collector, placements, - powerOutput: sized.power, - alternates: await finalizeAlternates( - collector, - placements, - sized.power, - effectiveBuildings, - ctx, - pacer, - ), - }; + tidied.power, + effectiveBuildings, + ctx, + pacer, + ); + // Every one of these ties on power, so the cheapest to build goes first and + // is the one the island shows. Stable, so equal costs keep the walk's order. + const [best, ...rest] = cheapestFirst( + [{ placements, powerOutput: tidied.power }, ...alternates], + (l) => l.placements, + ); + return { ...best, alternates: rest }; } /** @@ -721,6 +747,7 @@ export const internals = { DOWNGRADE_ROLES, constructMultiStartSeed, downgradeTiers, + gatherEmptyTiles, gatherPooledCoolers, greedyPolish, hillClimb, diff --git a/packages/solver/src/solver/search/emptyTiles.ts b/packages/solver/src/solver/search/emptyTiles.ts new file mode 100644 index 0000000..ca28164 --- /dev/null +++ b/packages/solver/src/solver/search/emptyTiles.ts @@ -0,0 +1,178 @@ +import type { IslandContext } from "../context"; +import { type SimPlacedBuilding, simulateIsland } from "../simulate"; +import type { EffectiveBuilding, Placement } from "../types"; +import { chebyshev, emptyPlacement, put } from "./placement"; +import { covers } from "./rightSize"; +import { anyOfflineProducer, planHolds } from "./stability"; + +/** + * Pushing the tiles a finished layout leaves empty out to the edge of the land + * and into its corners. + */ + +/** + * How long `gatherEmptyTiles` may spend, per solve on the primary layout and + * once more shared across its alternates. It runs after the search's deadline, + * so this is time added to a run; out of time, the holes stay where the sweep + * left them. On a desktop the largest shipped island under Singularity takes + * 105-145ms and the rest 0-60ms, so this leaves a phone room to finish. + */ +export const EMPTY_GATHER_BUDGET_MS = 300; + +/** A tile's 8-neighbourhood is complete when every neighbour is buildable. */ +const FULL_NEIGHBOURHOOD = 8; + +/** + * How far inside the land each tile sits, as one sortable figure: lower is + * nearer an edge, and on the edge itself, nearer a corner. + * + * Depth is the 8-neighbour step count from the nearest tile with a + * non-buildable neighbour — water, an obstacle or the board's edge — and the + * buildable-neighbour count breaks ties within a ring, which is what puts a + * corner (three) ahead of a straight edge (five). + */ +function interiority(ctx: IslandContext): Int32Array { + const depth = new Int32Array(ctx.n).fill(-1); + const queue: number[] = []; + for (let t = 0; t < ctx.n; t++) { + if (ctx.neighbors[t].length < FULL_NEIGHBOURHOOD) { + depth[t] = 0; + queue.push(t); + } + } + for (let head = 0; head < queue.length; head++) { + const t = queue[head]; + for (const u of ctx.neighbors[t]) { + if (depth[u] < 0) { + depth[u] = depth[t] + 1; + queue.push(u); + } + } + } + const score = new Int32Array(ctx.n); + for (let t = 0; t < ctx.n; t++) + score[t] = depth[t] * (FULL_NEIGHBOURHOOD + 1) + ctx.neighbors[t].length; + return score; +} + +/** Buildings on the board doing nothing at all, as the readout would call them idle. */ +function idleCount(placement: Placement, rows: SimPlacedBuilding[]): number { + let n = 0; + for (const r of rows) { + if (placement[r.idx] === null) continue; + if ( + r.powerGenerated <= 0 && + r.heatProduced <= 0 && + r.heatConsumed <= 0 && + r.coolingProvided <= 0 + ) + n++; + } + return n; +} + +/** + * Moves the empty tiles a finished layout leaves inside the land out towards + * its shore and corners. + * + * The search places by power and nothing else, so wherever a building did not + * pay for its tile there is a hole, and the holes land wherever the walk + * stopped — often in the middle of the hubs, where the player has to build + * around them and wonders whether the solver forgot a tile. A hole on the + * shore or in a corner reads as what it is. + * + * Like `downgradeOversized`, this cannot find a better layout. A hole moves by + * a building nearer the edge stepping into it, which leaves the hole on the + * building's old tile. That changes what the building stands beside, so every + * move is re-simulated and kept only if power holds against the layout handed + * in, every producer stays online, nothing new goes idle and the upgrade plan + * still runs. Any building nearer the edge may be offered, nearest first: a + * radius of two left 7 of 24 interior holes standing across the eight shipped + * maps under Singularity (a player's 160s solves), and no radius left none, + * at no power. + * + * Under a cooling pool coolers are not moved, since `gatherPooledCoolers` has + * just put them where they are. Every accepted move strictly lowers the holes' + * summed `interiority`, so the sweep terminates; the deadline only bounds how + * far it gets. + */ +export function gatherEmptyTiles( + rows: SimPlacedBuilding[], + power: number, + effectiveBuildings: EffectiveBuilding[], + ctx: IslandContext, + deadlineMs: number, +): { rows: SimPlacedBuilding[]; power: number } { + if (rows.length === 0 || rows.length >= ctx.n) return { rows, power }; + + const byId = new Map(effectiveBuildings.map((b) => [b.id, b])); + const current = emptyPlacement(ctx.n); + for (const row of rows) { + const building = byId.get(row.buildingId); + if (building === undefined) return { rows, power }; + put(current, ctx, row.idx, building); + } + + const score = interiority(ctx); + const pooled = ctx.anomaly.rule === "shared_cooling"; + const floor = power; + const idleFloor = idleCount(current, rows); + let moved = false; + + let changed = true; + while (changed && performance.now() < deadlineMs) { + changed = false; + // Deepest hole first: it has the furthest to go. + const holes: number[] = []; + for (let t = 0; t < ctx.n; t++) + if (current[t] === null && score[t] > 0) holes.push(t); + holes.sort((a, b) => score[b] - score[a] || a - b); + + for (const hole of holes) { + if (performance.now() >= deadlineMs) break; + // Nearest the hole first, since a building that moves a step keeps most + // of its neighbours; then nearest the edge, then ascending index, so the + // result depends only on the board. + const sources: number[] = []; + for (let t = 0; t < ctx.n; t++) { + const b = current[t]; + if (b === null || score[t] >= score[hole]) continue; + if (pooled && b.type === "cooler") continue; + sources.push(t); + } + sources.sort( + (a, b) => + chebyshev(ctx, a, hole) - chebyshev(ctx, b, hole) || + score[a] - score[b] || + a - b, + ); + + for (const from of sources) { + const building = current[from]!; + put(current, ctx, hole, building); + current[from] = null; + const trial = simulateIsland(current, ctx); + if ( + covers(trial.totalPower, floor) && + !anyOfflineProducer(current, trial.placements) && + idleCount(current, trial.placements) <= idleFloor && + planHolds(current, ctx) + ) { + changed = true; + moved = true; + break; + } + current[hole] = null; + put(current, ctx, from, building); + if (performance.now() >= deadlineMs) break; + } + } + } + + if (!moved) return { rows, power }; + const final = simulateIsland(current, ctx); + // Every kept move held the floor, so a shortfall here would be a bug rather + // than a trade. Give the input back. + if (!covers(final.totalPower, floor)) return { rows, power }; + return { rows: final.placements, power: final.totalPower }; +} diff --git a/packages/solver/src/solver/search/rightSize.ts b/packages/solver/src/solver/search/rightSize.ts index e5e5cc8..eeab458 100644 --- a/packages/solver/src/solver/search/rightSize.ts +++ b/packages/solver/src/solver/search/rightSize.ts @@ -134,7 +134,7 @@ export function downgradeTiers( * The sweep repeats to a fixpoint: downgrading a generator changes the waste * its cooler has to absorb, which can free a cooler this sweep already walked * past. It terminates because every accepted swap strictly lowers one tile's - * capacity and the ladders are finite. + * capacity, every accepted removal empties a tile, and the ladders are finite. * * Tiles are visited in ascending index order, which is the game's own spatial * order — see `context.ts`. @@ -168,12 +168,38 @@ export function downgradeOversized( changed = false; for (const tile of occupied) { - const building = current[tile]!; + const building = current[tile]; + // Taken away by the idle case below on an earlier sweep. + if (building === null) continue; const ladder = tiers.get(building.type); if (ladder === undefined || ladder.length === 0) continue; const load = tileLoad(building, rowAt.get(tile)!); + // Nothing to size: the building is doing nothing. Every tier covers a + // load of zero, so without this it would be swapped for the bottom of + // its ladder and left standing idle — and it does go idle after the + // prune, because shrinking a neighbour moves the split onto one cooler + // of two side by side and leaves the other with none. The smallest tier + // of an idle building is no building, under the same guard as a swap. + if (load <= 0) { + current[tile] = null; + const trial = simulateIsland(current, ctx); + if ( + covers(trial.totalPower, floor) && + !anyOfflineProducer(current, trial.placements) && + planHolds(current, ctx) + ) { + power = trial.totalPower; + rows = trial.placements; + rowAt.clear(); + for (const r of rows) rowAt.set(r.idx, r); + changed = true; + continue; + } + put(current, ctx, tile, building); + } + for (const candidate of ladder) { // Rated for this tile before it is compared to anything: `building` is // what the tile is running and `load` is what the layout measured it diff --git a/packages/solver/tests/buildingPrices.test.ts b/packages/solver/tests/buildingPrices.test.ts index 9f4185e..3732a4f 100644 --- a/packages/solver/tests/buildingPrices.test.ts +++ b/packages/solver/tests/buildingPrices.test.ts @@ -7,7 +7,13 @@ import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; -import { buildPrice, priceRules, sellRefund } from "../src/data/buildingPrices"; +import { + buildPrice, + cheapestFirst, + layoutCost, + priceRules, + sellRefund, +} from "../src/data/buildingPrices"; import { decodeGameExport } from "../src/encoding/gameExport"; const DIR = join(dirname(fileURLToPath(import.meta.url)), "gameExports"); @@ -53,3 +59,33 @@ describe("buildPrice and sellRefund", () => { expect(sellRefund(100, 0, rules)).toBe(0); }); }); + +describe("cheapestFirst", () => { + const at = (...ids: string[]) => ids.map((buildingId) => ({ buildingId })); + const order = (...layouts: { buildingId: string }[][]) => + cheapestFirst(layouts, (l) => l).map((l) => l.map((p) => p.buildingId)); + + it("puts the cheaper layout first", () => { + // Heat Sink #1 is 10, #2 is 125. + expect(order(at("cooler2"), at("cooler1"))).toEqual([ + ["cooler1"], + ["cooler2"], + ]); + }); + + it("charges every copy at the price the next one would be", () => { + expect(layoutCost(at("cooler1", "cooler1"))).toBeCloseTo(10 + 10 * 1.14, 9); + }); + + it("falls back to fewer buildings when the cost does not say", () => { + // Ids the catalogue does not price cost nothing, so only the count is left. + expect(order(at("x", "y"), at("x"))).toEqual([["x"], ["x", "y"]]); + }); + + it("keeps the incoming order where neither figure separates them", () => { + expect(order(at("y", "x"), at("x", "y"))).toEqual([ + ["y", "x"], + ["x", "y"], + ]); + }); +}); diff --git a/packages/solver/tests/placementSearch.downgrade.test.ts b/packages/solver/tests/placementSearch.downgrade.test.ts index eb17ce1..a2addfc 100755 --- a/packages/solver/tests/placementSearch.downgrade.test.ts +++ b/packages/solver/tests/placementSearch.downgrade.test.ts @@ -9,7 +9,8 @@ * player pays for the difference. * * What it may change is narrow, and that is what these pin: the tier on a tile, - * never which tiles are occupied, and never the power. + * never the power, and which tiles are occupied only by taking away a building + * the layout leaves doing nothing at all. * * Ported from `DowngradeOversizedTests` in the reference solver's * `tests/test_search.py`. @@ -119,6 +120,27 @@ describe("downgradeOversized", () => { expect(ids.get(2)!.buildingId).toBe("cooler_m"); }); + it("takes away an idle cooler rather than shrinking it", () => { + // Two coolers side by side, and only the first beside the generator: the + // second carries nothing. Every tier covers a load of zero, so before the + // pass learned this it became the cheapest cooler and stayed, idle. + const roster = [ + reactor(100), + generator(100), + cooler(10, "cooler_s"), + cooler(25, "cooler_m"), + ]; + const { before, after, ids } = sizeUp( + [roster[0], roster[1], roster[3], roster[3]], + roster, + ); + + expect(before.placements.find((r) => r.idx === 3)!.coolingProvided).toBe(0); + expect(after.power).toBeCloseTo(before.totalPower, 9); + expect(ids.has(3)).toBe(false); + expect(ids.get(2)!.buildingId).toBe("cooler_m"); + }); + it("downgrades a reactor to the heat it actually sends", () => { // The generator caps at 100, so 900 of the reactor's 1000 heat is never // absorbed and the tier producing it is paid for and idle. diff --git a/packages/solver/tests/placementSearch.emptyTiles.test.ts b/packages/solver/tests/placementSearch.emptyTiles.test.ts new file mode 100644 index 0000000..0371f63 --- /dev/null +++ b/packages/solver/tests/placementSearch.emptyTiles.test.ts @@ -0,0 +1,91 @@ +/** + * Pushing the holes a finished layout leaves out to the edge of the land. + * + * The pass can only move buildings, never change one, and never lose power; + * what this pins is that an interior hole does move, without costing either. + */ +import { describe, expect, it } from "vitest"; +import { buildIslandContext } from "../src/solver/context"; +import { internals } from "../src/solver/placementSearch"; +import { simulateIsland } from "../src/solver/simulate"; +import type { EffectiveBuilding, Placement, Tile } from "../src/solver/types"; + +const { gatherEmptyTiles } = internals; + +function cooler(value: number): EffectiveBuilding { + return { + id: "cooler", + type: "cooler", + effectiveValue: value, + energy: 0, + waste: 0, + baseValue: value, + }; +} + +function directProducer(value: number): EffectiveBuilding { + return { + id: "dp", + type: "direct_producer", + effectiveValue: value, + energy: value / 2, + waste: value / 2, + baseValue: value, + }; +} + +function grass(size: number): Tile[][] { + return Array.from({ length: size }, (_, y) => + Array.from({ length: size }, (_, x): Tile => ({ x, y, type: "grass" })), + ); +} + +/** A 5x5 board with `at` written in by (x, y). */ +function board(at: [number, number, EffectiveBuilding][]) { + const ctx = buildIslandContext(grass(5)); + const placement: Placement = new Array(ctx.n).fill(null); + for (const [x, y, b] of at) placement[tileAt(ctx, x, y)] = b; + return { ctx, sim: simulateIsland(placement, ctx) }; +} + +/** Tile indices follow the game's spatial order, not row-major. */ +function tileAt( + ctx: ReturnType, + x: number, + y: number, +): number { + for (let t = 0; t < ctx.n; t++) + if (ctx.xs[t] === x && ctx.ys[t] === y) return t; + throw new Error(`no tile at ${x},${y}`); +} + +describe("gatherEmptyTiles", () => { + it("fills the centre of the land and leaves the hole nearer the edge", () => { + // A producer above the centre and its cooler beside it, with the centre + // empty. The cooler still touches the producer from the centre, so it can + // step in and leave the hole one ring out. + const dp = directProducer(10); + const c = cooler(10); + const { ctx, sim } = board([ + [2, 1, dp], + [3, 1, c], + ]); + const roster = [dp, c]; + expect(sim.totalPower).toBeGreaterThan(0); + + const out = gatherEmptyTiles( + sim.placements, + sim.totalPower, + roster, + ctx, + Infinity, + ); + + const occupied = new Set(out.rows.map((r) => r.idx)); + expect(occupied.has(tileAt(ctx, 2, 2))).toBe(true); + expect(occupied.size).toBe(2); + expect(out.power).toBe(sim.totalPower); + const producer = out.rows.find((r) => r.buildingId === "dp")!; + expect(producer.powerGenerated).toBeGreaterThan(0); + }); +}); From 9221fa9a105a827ac02ced24af7b4480a4ac668c Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:28:45 +0300 Subject: [PATCH 2/3] Order tied layouts cheapest first, and pick each landmass's layout on its own Every shortlist the app keeps is now cheapest first: attempts pooled for one island, the whole-board variants, and a tied re-run, which follows the layout on screen to its new place. A later attempt is still judged against the best power reached, so a cheaper tie a hair below it cannot drag the island's figure down. On a board where two or more islands have layouts of their own to choose between, the card shows a Part picker per island. Stepping one swaps that island's layout and keeps the rest; the board that makes is scored and put into the shortlist, never growing it past ten. --- .../inspector/BoardStatsCard.svelte | 38 +++ src/lib/components/inspector/CLAUDE.md | 10 +- src/lib/state/solveVariants.test.ts | 99 ++++++- src/lib/state/solver.svelte.ts | 243 +++++++++++++++++- src/lib/worker/islandBest.test.ts | 29 +++ src/lib/worker/islandBest.ts | 40 ++- src/lib/worker/variants.ts | 11 +- 7 files changed, 445 insertions(+), 25 deletions(-) diff --git a/src/lib/components/inspector/BoardStatsCard.svelte b/src/lib/components/inspector/BoardStatsCard.svelte index bc814e8..cd62df1 100755 --- a/src/lib/components/inspector/BoardStatsCard.svelte +++ b/src/lib/components/inspector/BoardStatsCard.svelte @@ -114,6 +114,14 @@ solverState.variantCount > 1, ); + /* + * One picker per island when the board has two or more islands with layouts + * of their own to choose between — two big landmasses, typically. The + * whole-board cycler moves one island at a time across ten boards, so the + * mix a player wants is rarely one of them; these build it. + */ + let islandPickers = $derived(cycling ? solverState.islandPickers : []); + /* * Folded down to one line, on a small screen only. A desktop card sits in a * corner of a wide canvas; a phone card lies across the map being played. @@ -863,6 +871,36 @@ {/if} + {#each islandPickers as picker, i (picker.island)} +
+ Part {i + 1} + + + + {picker.current + 1} / {picker.choices.length} + + + +
+ {/each} {/if} {/if} diff --git a/src/lib/components/inspector/CLAUDE.md b/src/lib/components/inspector/CLAUDE.md index 36c046e..ef0e428 100644 --- a/src/lib/components/inspector/CLAUDE.md +++ b/src/lib/components/inspector/CLAUDE.md @@ -106,7 +106,15 @@ taking its cluster's output with it. **When the solve has ties, the card grows a Layout row** — arrows, `n / total`, and Apply. It renders only above one variant and never while a run is in flight: the shortlist that run will produce does not exist yet, and the layout streaming -into the panel is not one of its entries. +into the panel is not one of its entries. The shortlist is ordered cheapest +first (`cheapestFirst`), so `1 / n` is the cheapest board at that power. + +**Below it, a Part row per island** when two or more islands each have more than +one layout in the shortlist (`solverState.islandPickers`) — typically a board of +two big landmasses. Stepping one swaps that island's layout and leaves the rest +as shown; the board that makes is scored and appended to the shortlist +(`showIslandLayout`), so it previews, applies and is stored like any other +entry. Never under a cooling pool, where the board is one island. **Reset asks twice** and acts on whichever board is showing: the solve, or every hand-placed building. Switching panels disarms it, otherwise a press aimed at one diff --git a/src/lib/state/solveVariants.test.ts b/src/lib/state/solveVariants.test.ts index ad5f0ce..6f051a9 100755 --- a/src/lib/state/solveVariants.test.ts +++ b/src/lib/state/solveVariants.test.ts @@ -26,8 +26,13 @@ const store = new Map(); }; const { layoutState } = await import("./layout.svelte"); -const { solverState, chooseSolveVariants, composeIslandBests } = - await import("./solver.svelte"); +const { + solverState, + chooseSolveVariants, + composeIslandBests, + islandChoices, + withIslandLayout, +} = await import("./solver.svelte"); const { solverStorage } = await import("../storage/storage"); const { configState } = await import("./config.svelte"); const { SolverWorkerClient } = await import("../worker/workerClient"); @@ -129,6 +134,17 @@ describe("what a finished run does to the shortlist", () => { expect(chosen.selected).toBe(0); }); + it("puts a cheaper tie first and keeps the user on their layout", () => { + const held = [spread(500, 0), spread(500, 1)]; + // The same power from one building fewer: the cheapest of the three. + const cheaper = spread(500, 2); + cheaper.placements.pop(); + + const chosen = chooseSolveVariants(held, 1, [cheaper]); + expect(at(chosen.variants)).toEqual([2, 0, 1]); + expect(chosen.selected).toBe(2); + }); + it("replaces the shortlist outright when the run comes back higher", () => { const chosen = chooseSolveVariants([spread(500, 0)], 0, [spread(600, 1)]); expect(at(chosen.variants)).toEqual([1]); @@ -619,3 +635,82 @@ describe("what a re-run leaves on screen", () => { }); }); }); + +describe("a layout picker per island", () => { + // Two islands: x below 10 is the first, the rest the second. + const islandOf = (p: PlacedBuilding) => (p.x < 10 ? 0 : 1); + const tiles = new Map([ + [0, 40], + [1, 60], + ]); + const half = (id: string, x0: number) => + [0, 1, 2].map((k) => placed(id, x0 + k, 0)); + const board = (...halves: PlacedBuilding[][]) => { + const r = result(500, 0); + r.placements = halves.flat(); + return r; + }; + + it("offers each island the layouts the shortlist holds for it", () => { + const a0 = half("generator", 0); + const b0 = half("cooler1", 0); + const a1 = half("generator", 10); + const b1 = half("cooler1", 10); + const variants = [board(a0, a1), board(b0, a1), board(a0, b1)]; + + const pickers = islandChoices( + variants, + variants[0].placements, + islandOf, + tiles, + ); + // Largest first, each on the layout the board on screen has. + expect(pickers.map((p) => [p.island, p.choices.length, p.current])).toEqual( + [ + [1, 2, 0], + [0, 2, 0], + ], + ); + + // The mix none of the three boards is: both islands on their second. + const mixed = withIslandLayout( + variants[1].placements, + 1, + pickers[0].choices[1], + islandOf, + ); + expect(mixed.map((p) => p.buildingId)).toEqual(Array(6).fill("cooler1")); + }); + + it("leaves out an island the shortlist never varies", () => { + const a1 = half("generator", 10); + const variants = [ + board(half("generator", 0), a1), + board(half("cooler1", 0), a1), + ]; + const pickers = islandChoices( + variants, + variants[0].placements, + islandOf, + tiles, + ); + expect(pickers.map((p) => p.island)).toEqual([0]); + }); + + it("counts an island left empty as one of its layouts", () => { + const a0 = half("generator", 0); + const a1 = half("generator", 10); + const b1 = half("cooler1", 10); + const variants = [board(a0, a1), board(b1), board(a0, b1)]; + + const pickers = islandChoices( + variants, + variants[1].placements, + islandOf, + tiles, + ); + const first = pickers.find((p) => p.island === 0)!; + expect(first.choices.map((c) => c.length)).toEqual([3, 0]); + expect(first.current).toBe(1); + }); +}); diff --git a/src/lib/state/solver.svelte.ts b/src/lib/state/solver.svelte.ts index 5acb06b..7c6a223 100755 --- a/src/lib/state/solver.svelte.ts +++ b/src/lib/state/solver.svelte.ts @@ -23,7 +23,12 @@ import { } from "../worker/solveModes"; import { BUILDINGS } from "@reactor2/solver"; import { getEffectiveBuildings } from "@reactor2/solver"; -import { isDistinctLayout, powerTies } from "@reactor2/solver"; +import { + cheapestFirst, + isDistinctLayout, + layoutKey, + powerTies, +} from "@reactor2/solver"; import { canCoolDirectProducer, countGrassTiles, @@ -73,9 +78,10 @@ const WATCHDOG_GRACE_MS = 5_000; * A fresh layout joins only if it is `MIN_ALTERNATE_DISTANCE` tiles away from * every layout already in the list — two runs finding the same arrangement is * common and it is one answer, not two, and two runs finding it a cooler apart - * is the same again. Held layouts stay in front, and go in unfiltered so the - * applied one keeps its index: a shortlist stored without that rule would - * otherwise lose an entry ahead of the user's pick and shift it. + * is the same again. Held layouts go in unfiltered: a shortlist stored without + * that rule would otherwise lose an entry. The pooled list is then put + * cheapest first (`cheapestFirst`), as every shortlist is, and `selected` + * follows the layout the user was on to wherever that puts it. * * **The bar is the best layout held, not the one being looked at.** Cycling is * a preview, so `heldIndex` is wherever the user's eye happens to be — and a @@ -103,12 +109,14 @@ export function chooseSolveVariants( return { variants: fresh.slice(0, limit), selected: 0, defended: false }; // A stored index can outrun a shortlist that has since been rebuilt; the - // first entry is the layout the search settled on, so it is the safe home. + // first entry is the cheapest at the shortlist's power, so it is a safe home. const selected = Math.min(Math.max(heldIndex, 0), held.length - 1); // Under an upgrade plan `rank` is the power *after* the plan, which is what // the search maximised; `totalPower` is today's, which it did not. const bestHeldPower = Math.max(...held.map(rank)); - const freshPower = rank(fresh[0]); + // The best of the fresh shortlist, not its first entry: that is the + // cheapest of its ties, which may sit a hair below the run's best. + const freshPower = Math.max(...fresh.map(rank)); if (powerTies(freshPower, bestHeldPower)) { const variants = held.slice(); @@ -123,7 +131,14 @@ export function chooseSolveVariants( continue; variants.push(variant); } - return { variants, selected, defended: false }; + const onScreen = variants[selected]; + // Stable, so equal costs keep held layouts ahead of fresh ones. + const ranked = cheapestFirst(variants, (v) => v.placements); + return { + variants: ranked, + selected: ranked.indexOf(onScreen), + defended: false, + }; } if (bestHeldPower > freshPower) { @@ -204,6 +219,86 @@ export function composeIslandBests( return composed; } +/** One island's own layouts, out of a shortlist of whole boards. */ +export interface IslandChoices { + /** The island, as `islandOf` numbers it. */ + island: number; + /** Its buildable tiles, which is what orders the pickers largest first. */ + tiles: number; + /** Each distinct layout of this island the shortlist holds, in its order. */ + choices: PlacedBuilding[][]; + /** Which of them `current` has on this island. */ + current: number; +} + +/** + * The islands a player can choose a layout for one at a time: every island + * that more than one board in the shortlist lays out differently, largest + * first. + * + * The shortlist holds whole boards, so on a board of two big landmasses its + * entries mostly move one landmass at a time and the combination the player + * wants — this one's second layout with that one's third — is usually not in + * it. Islands never interact, so any mix is a legal board; this is what lets + * the card offer a picker per island instead. + */ +export function islandChoices( + variants: readonly OptimizationResult[], + current: readonly PlacedBuilding[], + islandOf: (p: PlacedBuilding) => number, + tiles: ReadonlyMap, +): IslandChoices[] { + const split = (placements: readonly PlacedBuilding[]) => { + const byIsland = new Map(); + for (const p of placements) { + const k = islandOf(p); + if (k < 0) continue; + const rows = byIsland.get(k); + if (rows) rows.push(p); + else byIsland.set(k, [p]); + } + return byIsland; + }; + + const choices = new Map>(); + for (const variant of variants) { + const byIsland = split(variant.placements); + // Every island, built on or not: a board leaving an island empty is one + // of that island's layouts too, and the picker has to be able to reach it. + for (const k of tiles.keys()) { + const rows = byIsland.get(k) ?? []; + let seen = choices.get(k); + if (!seen) choices.set(k, (seen = new Map())); + const key = layoutKey(rows); + if (!seen.has(key)) seen.set(key, rows); + } + } + + const onScreen = split(current); + const out: IslandChoices[] = []; + for (const [island, seen] of choices) { + if (seen.size < 2) continue; + const keys = [...seen.keys()]; + out.push({ + island, + tiles: tiles.get(island) ?? 0, + choices: [...seen.values()], + current: keys.indexOf(layoutKey(onScreen.get(island) ?? [])), + }); + } + return out.sort((a, b) => b.tiles - a.tiles || a.island - b.island); +} + +/** `current` with `island`'s buildings replaced by `layout`. */ +export function withIslandLayout( + current: readonly PlacedBuilding[], + island: number, + layout: readonly PlacedBuilding[], + islandOf: (p: PlacedBuilding) => number, +): PlacedBuilding[] { + return [...current.filter((p) => islandOf(p) !== island), ...layout]; +} + /** * A layout stripped to what storage keeps: which building, where, and the tier * it was placed at. Everything else is re-derived by scoring it — see @@ -438,8 +533,7 @@ class SolverState { * Zero when there is nothing to solve, which is also when there is no figure * worth showing. */ - estimateRunMs(mode: SolveMode): number { - const grid = layoutState.grid; + estimateRunMs(mode: SolveMode, grid: Tile[][] = layoutState.grid): number { if (!grid || !grid.length || !grid[0] || !grid[0].length) return 0; const effectiveBuildings = getEffectiveBuildings( @@ -545,6 +639,137 @@ class SolverState { this.#persistCurrent(); } + /** + * Which island each placement stands on, split the way a run under the + * result's anomaly splits the board on screen, and each island's size. + */ + #islandIndex(): { + islandOf: (p: PlacedBuilding) => number; + tiles: Map; + } { + const grid = layoutState.grid; + const width = grid[0]?.length ?? 0; + const islands = splitGridIntoIslands( + grid, + canCoolDirectProducer( + getEffectiveBuildings( + BUILDINGS, + configState.buildingUpgrades, + configState.prestige, + ), + ), + getAnomaly(this.resultAnomalyId ?? configState.activeAnomaly.id), + ); + const islandAt = new Map(); + const tiles = new Map(); + islands.forEach((island, i) => { + tiles.set(i, island.tileCount); + island.originalTileIndices.forEach((tile, k) => { + if (island.buildable[k] === 1) islandAt.set(tile, i); + }); + }); + return { + islandOf: (p) => islandAt.get(p.y * width + p.x) ?? -1, + tiles, + }; + } + + /** + * A layout picker per island, for a board where at least two islands each + * have more than one layout at this power — empty otherwise, and the + * whole-board cycler says everything there is to say. Under a shared + * cooling pool the board is one island, so there is never more than one. + */ + get islandPickers(): IslandChoices[] { + const result = this.optimizationResult; + if (!result || this.variants.length < 2) return []; + const { islandOf, tiles } = this.#islandIndex(); + const pickers = islandChoices( + this.variants, + result.placements, + islandOf, + tiles, + ); + return pickers.length >= 2 ? pickers : []; + } + + /** + * Steps one island to its next (or, with `delta` -1, previous) layout and + * leaves every other island as it is on screen. + * + * The board that makes is often not in the shortlist, since the shortlist + * moves one island at a time. It is scored and put into it (`#mixSlot`), so + * it previews, applies and is stored like any other entry. A mix that does not tie the + * board on screen is skipped. Islands never interact, so mixing ties should + * always tie, but a shortlist pooled across runs and re-rated at a new + * roster is not guaranteed to be level island by island. + */ + showIslandLayout(island: number, delta: 1 | -1) { + const result = this.optimizationResult; + if (!result) return; + const { islandOf, tiles } = this.#islandIndex(); + const picker = islandChoices( + this.variants, + result.placements, + islandOf, + tiles, + ).find((c) => c.island === island); + if (!picker) return; + + const count = picker.choices.length; + let bound: number | null = null; + for (let step = 1; step < count; step++) { + const next = (((picker.current + delta * step) % count) + count) % count; + const placements = withIslandLayout( + result.placements, + island, + picker.choices[next], + islandOf, + ); + const key = layoutKey(placements); + const existing = this.variants.findIndex( + (v) => layoutKey(v.placements) === key, + ); + if (existing >= 0) { + this.showVariant(existing); + return; + } + bound ??= this.estimatedMaxPower; + const scored = this.#scoreLayout(placements, bound); + if (!powerTies(scored.totalPower, result.totalPower)) continue; + const slot = this.#mixSlot(); + const variants = this.variants.slice(); + if (slot < 0) variants.push(scored); + else variants[slot] = scored; + this.#mixes.add(scored); + this.variants = variants; + this.showVariant(slot < 0 ? variants.length - 1 : slot); + return; + } + } + + /** Boards `showIslandLayout` made, as opposed to ones a run found. */ + #mixes = new WeakSet(); + + /** + * Where `showIslandLayout` puts a board it made, -1 for "append": over the + * one it made last if that is on screen and not applied, so stepping a + * picker does not leave a trail; otherwise appended while the shortlist has + * room; otherwise over the dearest entry that is not applied — the list is + * cheapest first, so that is the last. The shortlist never outgrows + * `MAX_SOLVE_VARIANTS` this way, which a re-run's pooling relies on: a held + * list already at the limit takes nothing fresh. + */ + #mixSlot(): number { + const on = this.variantIndex; + if (on !== this.appliedVariant && this.#mixes.has(this.variants[on])) + return on; + if (this.variants.length < MAX_SOLVE_VARIANTS) return -1; + for (let i = this.variants.length - 1; i >= 0; i--) + if (i !== this.appliedVariant) return i; + return -1; + } + /** * Identity of the board and roster a solve was computed against. * diff --git a/src/lib/worker/islandBest.test.ts b/src/lib/worker/islandBest.test.ts index 2c4d4f2..42197b6 100755 --- a/src/lib/worker/islandBest.test.ts +++ b/src/lib/worker/islandBest.test.ts @@ -144,4 +144,33 @@ describe("IslandBest", () => { expect(shapes(best)).toHaveLength(3); // primary + 2 alternates }); + + it("makes the cheaper of two tied layouts the primary", () => { + const best = new IslandBest(); + best.offer(layout("cooler2", 0, 100)); + best.offer(layout("cooler1", 1, 100)); + expect(shapes(best)).toEqual(["cooler1@1", "cooler2@0"]); + }); + + it("lets a cheaper tie push the dearest out of a full shortlist", () => { + const best = new IslandBest(1); + best.offer({ + ...layout("cooler2", 0, 100), + alternates: [layout("cooler3", 1, 100)], + }); + best.offer(layout("cooler1", 2, 100)); + expect(shapes(best)).toEqual(["cooler1@2", "cooler2@0"]); + }); + + it("holds later attempts to the best power reached, not the cheapest's", () => { + // Ties are relative (1e-9), so a cheaper tie can sit a hair under the + // best. Measured from it, a third attempt a hair under *that* would tie + // too, and the island's figure would creep down. + const best = new IslandBest(); + const p = 1e20; + best.offer(layout("cooler3", 0, p)); + best.offer(layout("cooler2", 1, p - 0.6e11)); + best.offer(layout("cooler1", 2, p - 1.2e11)); + expect(shapes(best)).toEqual(["cooler2@1", "cooler3@0"]); + }); }); diff --git a/src/lib/worker/islandBest.ts b/src/lib/worker/islandBest.ts index a89ed75..0dc44d7 100755 --- a/src/lib/worker/islandBest.ts +++ b/src/lib/worker/islandBest.ts @@ -1,4 +1,9 @@ -import { isDistinctLayout, powerTies, MAX_ALTERNATES } from "@reactor2/solver"; +import { + cheapestFirst, + isDistinctLayout, + powerTies, + MAX_ALTERNATES, +} from "@reactor2/solver"; import type { IslandSolution } from "@reactor2/solver"; import type { IslandLayout, PlacedBuilding } from "@reactor2/solver"; @@ -28,6 +33,14 @@ import type { IslandLayout, PlacedBuilding } from "@reactor2/solver"; * own shortlist (`MIN_ALTERNATE_DISTANCE`), so two attempts converging on the * same arrangement — common, and the usual case on a small island — count * once, and so do two that converged a tile apart. + * + * **Cheapest first.** Everything held ties on power, so the pool is kept + * ordered by `cheapestFirst` and its head is the primary: an attempt that + * found the same power for less takes the island over, and once the shortlist + * is full a cheaper newcomer pushes out the dearest entry. A later attempt is + * still judged against the best power any attempt reached, not the primary's: + * a tie may sit a hair below the bar, and measuring from the cheapest would let + * the island's figure creep down one tolerance at a time. */ export class IslandBest { #primary: IslandLayout = { placements: [], powerOutput: 0 }; @@ -35,6 +48,8 @@ export class IslandBest { /** The primary and every alternate kept, for the distance test. */ #kept: PlacedBuilding[][] = []; #settled = false; + /** The best power any attempt reached — the bar the next one is held to. */ + #bar = 0; readonly #limit: number; /** `limit` caps the alternates kept, matching what one search would keep. */ @@ -64,14 +79,14 @@ export class IslandBest { * coordinator streams those to the screen on a separate track. */ offer(candidate: IslandSolution): void { - const ties = - this.#settled && - powerTies(candidate.powerOutput, this.#primary.powerOutput); + const ties = this.#settled && powerTies(candidate.powerOutput, this.#bar); - if (!ties) { - if (this.#settled && candidate.powerOutput <= this.#primary.powerOutput) - return; + if (ties) { + this.#bar = Math.max(this.#bar, candidate.powerOutput); + } else { + if (this.#settled && candidate.powerOutput <= this.#bar) return; this.#settled = true; + this.#bar = candidate.powerOutput; this.#primary = { placements: candidate.placements, powerOutput: candidate.powerOutput, @@ -93,11 +108,18 @@ export class IslandBest { ] : (candidate.alternates ?? []); + const pool = [this.#primary, ...this.#alternates]; for (const layout of incoming) { - if (this.#alternates.length >= this.#limit) break; if (!isDistinctLayout(layout.placements, this.#kept)) continue; this.#kept.push(layout.placements); - this.#alternates.push(layout); + pool.push(layout); } + const ranked = cheapestFirst(pool, (l) => l.placements).slice( + 0, + this.#limit + 1, + ); + this.#primary = ranked[0]; + this.#alternates = ranked.slice(1); + this.#kept = ranked.map((l) => l.placements); } } diff --git a/src/lib/worker/variants.ts b/src/lib/worker/variants.ts index ca9441a..727d1ad 100755 --- a/src/lib/worker/variants.ts +++ b/src/lib/worker/variants.ts @@ -1,5 +1,5 @@ import { buildOptimizationResult, type IslandPlan } from "@reactor2/solver"; -import { layoutKey, powerTies } from "@reactor2/solver"; +import { cheapestFirst, layoutKey, powerTies } from "@reactor2/solver"; import type { IslandSolution } from "@reactor2/solver"; import type { OptimizationResult } from "@reactor2/solver"; @@ -24,8 +24,10 @@ import type { OptimizationResult } from "@reactor2/solver"; export const MAX_SOLVE_VARIANTS = 10; /** - * All of them, best first: `[0]` is the layout the search actually settled on, - * and everything after it ties that layout's power. + * All of them, cheapest first (`cheapestFirst`): every one ties the power + * of the layout the search settled on, and `[0]` is the one of them that costs + * the least to build — which, with each island's own shortlist already in + * that order, is usually that layout. */ export function buildSolveVariants( plan: IslandPlan, @@ -74,5 +76,6 @@ export function buildSolveVariants( take(swapped); } - return variants; + // Stable, so equal costs keep the order they were generated in. + return cheapestFirst(variants, (v) => v.placements); } From eaa29003c69a57b0e5edf23388ddd3671a2f6b8f Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:28:45 +0300 Subject: [PATCH 3/3] Estimate Solve all per island, and keep it one run between islands The estimate was the island on screen times the island count, so it moved with whichever island was open. It is now each island's own estimate, summed, from boards decoded once in the background and replaced when an island is edited. Between two islands the solver is idle while the next board loads, and Setup flashed back in while Run showed for a beat. A batch now counts as one run throughout: Setup stays hidden, the button stays on Stop, and Stop in the gap ends the batch. --- src/App.svelte | 2 +- src/lib/components/hud/BoardActions.svelte | 4 +- .../components/sidebar/SolveAllButton.svelte | 14 +-- src/lib/state/solveAll.test.ts | 91 +++++++++++++++++++ src/lib/state/ui.svelte.ts | 84 ++++++++++++++++- 5 files changed, 179 insertions(+), 16 deletions(-) diff --git a/src/App.svelte b/src/App.svelte index 1c8e644..0e59981 100755 --- a/src/App.svelte +++ b/src/App.svelte @@ -32,7 +32,7 @@ * islands included: a phone that sleeps mid-run freezes the page with it. */ $effect(() => { - keepScreenAwake(solverState.isOptimizing || uiState.solveAll !== null); + keepScreenAwake(uiState.running); }); $effect(() => () => keepScreenAwake(false)); diff --git a/src/lib/components/hud/BoardActions.svelte b/src/lib/components/hud/BoardActions.svelte index f3c3ddf..e12c557 100755 --- a/src/lib/components/hud/BoardActions.svelte +++ b/src/lib/components/hud/BoardActions.svelte @@ -1,5 +1,5 @@ {#if uiState.canSolveAll} diff --git a/src/lib/state/solveAll.test.ts b/src/lib/state/solveAll.test.ts index 1ad8d93..5de3e4f 100644 --- a/src/lib/state/solveAll.test.ts +++ b/src/lib/state/solveAll.test.ts @@ -22,6 +22,7 @@ const store = new Map(); const { applyInProgress, + BUILDINGS, decodeGameExport, ISLAND_TEMPLATES, resolveGameExport, @@ -115,6 +116,26 @@ describe("solve all islands", () => { expect(uiState.solveAll).toBeNull(); }); + /* + * Between two islands the solver is idle while the next board loads. Setup + * used to key on the solver alone, so it flashed back in there, and Run + * showed where a press would have started a second solve beside the batch. + */ + it("keeps Setup hidden and Run as Stop between islands", async () => { + const seen: { hidden: boolean; running: boolean }[] = []; + solverState.runOptimizer = async () => { + // Called with the solver still idle: the gap between two islands. + seen.push({ hidden: uiState.setupHidden, running: uiState.running }); + }; + + await uiState.solveAllIslands(); + + expect(seen.length).toBeGreaterThan(1); + expect(seen.every((s) => s.hidden && s.running)).toBe(true); + expect(uiState.running).toBe(false); + expect(uiState.setupHidden).toBe(false); + }); + it("solves every shipped island when nothing has been imported", () => { expect(uiState.solveAllTargets.map((t) => t.id)).toEqual( ISLAND_TEMPLATES.filter((t) => t.game).map((t) => t.id), @@ -153,4 +174,74 @@ describe("solve all islands", () => { } expect(calls).toHaveLength(0); }); + + /* + * The estimate used to be the island on screen times the island count. An + * island in several pieces packs onto the pool differently from one in a + * single piece, so its own figure differs — on a four-core phone, Quick on a + * split island can come out at 24s against everyone else's 30s — and the + * total moved with whichever island was open. Each island is counted at its + * own figure now, which takes its board decoding in the background first. + */ + it("estimates the same total whichever island is open", async () => { + // Not an earlier case's import: its anomaly may be a cooling pool, which + // makes every map one island and every estimate alike. + const anomaly = configState.anomalyId; + configState.anomalyId = "none"; + const roster = configState.buildingUpgrades; + configState.buildingUpgrades = Object.fromEntries( + BUILDINGS.map((b) => [b.id, b.levels.length - 1]), + ); + Object.defineProperty(globalThis.navigator, "hardwareConcurrency", { + value: 4, + configurable: true, + }); + const mode = solverState.solveModeId; + solverState.solveModeId = "quick"; + try { + // The shipped maps, obstacles and all, at every building's top tier: + // several are split into pieces that pack onto the pool unevenly. + const targets = uiState.solveAllTargets; + const own = new Map(); + for (const t of targets) { + await layoutState.loadTemplate(t, configState.buildingUpgrades); + own.set(t.id, solverState.estimatedRunMs); + } + const low = targets.reduce((a, b) => + own.get(b.id)! < own.get(a.id)! ? b : a, + ); + const high = targets.reduce((a, b) => + own.get(b.id)! > own.get(a.id)! ? b : a, + ); + // Otherwise the old reading would pass too. + expect(own.get(low.id)).toBeLessThan(own.get(high.id)!); + + const settled = async () => { + let last = -1; + for (let i = 0; i < 50; i++) { + const now = uiState.solveAllEstimateMs; + if (now === last) return now; + last = now; + await new Promise((r) => setTimeout(r, 20)); + } + return last; + }; + await layoutState.loadTemplate(low, configState.buildingUpgrades); + const fromLow = await settled(); + await layoutState.loadTemplate(high, configState.buildingUpgrades); + const fromHigh = await settled(); + + expect(fromLow).toBeCloseTo(fromHigh, 6); + const sum = [...own.values()].reduce((a, b) => a + b, 0); + expect(fromHigh).toBeCloseTo(sum, 6); + } finally { + solverState.solveModeId = mode; + configState.buildingUpgrades = roster; + configState.anomalyId = anomaly; + // The stub is an own property shadowing the prototype's getter; + // deleting it puts the real core count back for whatever runs next. + delete (globalThis.navigator as { hardwareConcurrency?: number }) + .hardwareConcurrency; + } + }); }); diff --git a/src/lib/state/ui.svelte.ts b/src/lib/state/ui.svelte.ts index e335882..bb8b665 100755 --- a/src/lib/state/ui.svelte.ts +++ b/src/lib/state/ui.svelte.ts @@ -763,10 +763,11 @@ class UIState { // one. This is the backstop for the keyboard and for anything that reaches // the verb another way. if (this.isPreview) return; - if (solverState.isOptimizing) { - // Stop ends a "Solve all" too, not just the island it is on. + if (this.running) { + // Stop ends a "Solve all" too, not just the island it is on — and + // between two of its islands there is no search to stop, only the batch. if (this.solveAll) this.#solveAllCancelled = true; - solverState.stopOptimizer(); + if (solverState.isOptimizing) solverState.stopOptimizer(); return; } /* @@ -864,6 +865,70 @@ class UIState { return ISLAND_TEMPLATES.filter((t) => t.game && !locked.includes(t.id)); } + /** + * Each Solve all island's terrain, decoded in the background for the + * estimate: one entry per island, with the code it was decoded from — the + * player's saved board where there is one, the shipped map otherwise. An + * edit changes the code, and the entry is replaced rather than added to, so + * this never holds more than one board per island. Raw: whole boards are + * not worth proxying. + */ + #estimateGrids = $state.raw>( + {}, + ); + /** + * The code each island's decode was started for, while it runs — and after + * it fails, so a code that cannot be read is not decoded again on every + * recompute. The next edit changes the code and tries once more. + */ + #estimateDecoding = new Map(); + + /** `#estimateGrids` for one island, starting its decode if it has none yet. */ + #estimateGrid(template: IslandTemplate): Tile[][] | undefined { + const id = template.id; + const code = layoutState.savedGrids[id]?.code ?? template.code; + const held = this.#estimateGrids[id]; + if (held?.code === code) return held.grid; + if (this.#estimateDecoding.get(id) === code) return undefined; + this.#estimateDecoding.set(id, code); + void decodeBlueprint(code) + .then((decoded) => { + // Edited again while this decoded: a newer decode owns the entry. + if (this.#estimateDecoding.get(id) !== code) return; + this.#estimateDecoding.delete(id); + this.#estimateGrids = { + ...this.#estimateGrids, + [id]: { code, grid: decoded.grid }, + }; + }) + .catch(() => { + // Left out: the island borrows the on-screen estimate, as below. + }); + return undefined; + } + + /** + * About how long Solve all takes in the current mode: each island's own + * run, summed. Islands differ several times over in size, so the island on + * screen times the island count — what this was — moved with whichever + * island happened to be open. The one on screen is read live, edits and + * all; one still decoding borrows its figure for the moment. + */ + get solveAllEstimateMs(): number { + const mode = solverState.solveMode; + const onScreen = solverState.estimateRunMs(mode); + let total = 0; + for (const template of this.solveAllTargets) { + if (template.id === layoutState.activeTemplateId) { + total += onScreen; + continue; + } + const grid = this.#estimateGrid(template); + total += grid ? solverState.estimateRunMs(mode, grid) : onScreen; + } + return total; + } + /** Whether "Solve all" can start now — the controls are hidden otherwise. */ get canSolveAll(): boolean { return ( @@ -1188,7 +1253,18 @@ class UIState { * Stop is untouched — it lives in the HUD, which stays. */ get setupHidden(): boolean { - return solverState.isOptimizing; + return this.running; + } + + /** + * Whether a run is under way, counting a whole "Solve all" as one: between + * two of its islands the solver is idle for a moment while the next board + * loads, and anything keyed on `isOptimizing` alone flickered there — + * Setup flashed back in, and Run showed for a beat, where a press would + * have started a second solve beside the batch. + */ + get running(): boolean { + return solverState.isOptimizing || this.solveAll !== null; } toggleSidebar() {